﻿var resource_overviewName = "鹰眼";
var resource_findPathLength = "长度为";
var resource_findPathIsNull = "没有路径可达";
var resource_passedEdges = "经过的边数为";
var resource_passedNodes = "经过的中间节点为";
var resource_clearHighlight = "清除高亮";
var resource_findPathName = "路径分析结果";
var resource_findPathError = "路径分析出错";
var resource_queryResultIsNull = "查询结果为空";
var resource_busSolutionLength = "公交换乘方案总数为";
var resource_busSolutionName = "方案";
var resource_ride = "乘坐";
var resource_getOn = "上车";
var resource_bus = "汽车";
var resource_getDown = "下车";
var resource_busSolutionIsNull = "没有公交方案";
var resource_selectStartStop = "起点";
var resource_selectEndStop = "终点";
var resource_passStartLines = "经过起点的线路";
var resource_passEndLines = "经过终点的线路";
var resource_query = "查询";
var resource_busSolutionError = "公交分析出错";
var resource_findBusStopCount = "找到的站点个数为";
var resource_clearBusStopHighlight = "清除站点高亮";
var resource_findBusStopIsNull = "没有找到公交站点";
var resource_findBusStopError = "FindBusStop出错";
var resource_findBusLineCount = "找到的线路条数为";
var resource_clearBusLineHigthlight = "清除线路高亮";
var resource_findBusLineIsNull = "没有找到公交线路";
var resource_findBusLineError = "FindBusLine出错";
var resource_showBusStopError = "ShowBusStop出错";
var resource_showBusLineError = "ShowBusLine出错";
var resource_showRoutingError = "ShowRouting出错";
var resource_getBusLinesByStopID = "GetBusLinesByStopID出错";
var resource_inputStartStop = "请输入起始点";
var resource_inputEndStop = "请输入终止点";
var resource_inputLindId = "请输入线路ID";
var resource_inputStopId = "请输入站点ID";
var resource_inputBusRouting = "请输入换乘路径";
var resource_measureDistanceLength = "长度为";
var resource_measureResultIsNull = "没有量算结果";
var resource_measureDistanceError = "量算距离出错";
var resource_measureAreaLength = "面积为";
var resource_maesureAraeError = "量算面积出错";
var resource_queryError = "查询出错";
var resource_east = "正东";
var resource_northeast = "东北";
var resource_north = "正北";
var resource_northwest = "西北";
var resource_west = "正西";
var resource_southwest = "西南";
var resource_south = "正南";
var resource_southeast = "东南";
var resource_return = "返回";
var resource_toward = "往";
var resource_at = "在";
var resource_direction = "方向走";
var resource_deleteComfirm = "删除后不能恢复，确定删除？";
var resource_unvisible = "不可见";
var resource_visible = "可见";
var resource_unqueryable = "不可查";
var resource_queryable = "可查";
var resource_deleteLabelTheme = "删除标签专题图";
var resource_createLabelTheme = "创建标签专题图";
var resource_selectEntity = "请先选取对象";
var resource_styleSetting = "样式设定";
var resource_brushStyle = "填充模式";
var resource_brushColor = "填充颜色";
var resource_brushBackColor = "背景颜色";
var resource_penStyle = "边线线型";
var resource_penColor = "边线颜色";
var resource_penWidth = "边线宽度";
var resource_symbolStyle = "符号风格";
var resource_symbolSize = "符号大小";
var resource_btnOk = "确定";
var resource_inputInfo = "填写信息";
var resource_title = "名称";
var resource_description = "说明";
var resource_removeGeometry = "删除";
var resource_squareMeter = "平方米";
var resource_meter = "米";
var resource_modify = "修改";
var resource_noNamePoint = "未命名点";
var resource_noNameLine = "未命名线";
var resource_noNamePolygon = "未命名多边形";
var resource_getWorkspaceInfoError = "获取工作空间信息失败";
var resource_updateCoord = "更新坐标请单击地图中的相应位置";
var resource_busStopName = "站名";
var resource_lockLayerError = "锁定图层失败，可能其他用户已锁定此图层，请稍后再试";
var resource_unlockLayerError = "解锁图层失败，请稍后再试";
/*------split line-------*/
var MapControl1 = null;
var panAction = null;
var zoomInAction = null;
var zoomOutAction = null;
var pointQueryAction = null;
var lineQueryAction = null;
var findPathAction = null;
var getCoordsAction = null;
var former_index = 0;
var max_btn_number = 55;
var m_busSolution = null;
//公交换乘时出现选择换乘站点界面时，会先分加别对默认起始站点和终止站点调用GetBusLinesByStopID
//这对于异步的Ajax来说不太好控制结果的返回，所以在这里用busSolutionStep来控制
//false：正常情况
//true：还要对终止站点进行GetBusLinesByStopID
var busSolutionStep = false;
var measureDistanceAction = null;
var measureAreaAction = null;
var rectQueryAction = null;
var polygonQueryAction = null;
var circleQueryAction = null;
var currentRouting = null;
var drawPolygonAction = null;
var drawPointAction = null;
var drawLineAction = null;
var defaultStyle = null;
var bPasueDynamicNavigate = false;
var geometryObjects = new Array();
var brushResource = new Array();
var penResource = new Array();
var symbolResource = new Array();
var colorHex = new Array('00', '33', '66', '99', 'CC', 'FF');
var spColorHex = new Array('FF0000', '00FF00', '0000FF', 'FFFF00', '00FFFF', 'FF00FF');
var currentElement = null;
var startMoving = null;
var dragContainer = null;
var m_workspace = null;
var m_layers = null;
var tolerance = 200; //默认点选容限
var lockID = null;
var TcUrl = null;//页面跳转存放坐标
var Cdzbx = null;//周边查询点的x
var Cdzby = null;//周边查询点点y
var Qszbx = null;//起始坐标x
var Qszby = null;//起始坐标y
var Zdzbx = null;//终点坐标x
var Zdzby = null;//终点坐标y
 var tables = "POI@SXWebMeta";

function ImagesLoad(eventArg) {
    window.status = "loaded" + new Date().getTime();
}

function UpdateInfo(eventArg) {
    var info = document.getElementById("info");
    if (!info) { return false; }

    if (eventArg.param == null) {
        info.innerHTML = '<font color="red">error: ' + eventArg.error + '</font>';
        return false;
    }

    info.innerHTML = 'mapName = ' + eventArg.param.mapName + ', zoomLevel=' + eventArg.param.zoomLevel + ', mapCenter = '
            + eventArg.param.mapCenter.ToString() + ', pixelCenter = ' + eventArg.param.pixelCenter.ToString();
}
function ViewEntire() {
    MapControl1.ViewEntire();
}

function SetGetCoordsAction(num) {
    if (!getCoordsAction) {
        getCoordsAction = new GetCoordsAction(num);
    }
    MapControl1.SetAction(getCoordsAction);
}

function SetZoomInAction() {
    if (!zoomInAction) {
        zoomInAction = new SuperMap.IS.ZoomInAction();
    }
    MapControl1.SetAction(zoomInAction);
}

function SetZoomOutAction() {
    if (!zoomOutAction) {
        zoomOutAction = new SuperMap.IS.ZoomOutAction();
    }
    MapControl1.SetAction(zoomOutAction);
}

function SetPanAction() {
    if (!panAction) {
        panAction = new SuperMap.IS.PanAction();
    }
    MapControl1.SetAction(panAction);
}

function SetDrawLineAction() {
    var drawLineAction = new SuperMap.IS.DrawLineAction();
    MapControl1.SetAction(drawLineAction);
}

function SetPointQueryAction() {
    var layersInfo = GetQueryableFromLegend();
    var whereClause = GetWhereClause();
    pointQueryAction = new SuperMap.IS.PointQueryAction(layersInfo, null, tolerance, whereClause, OnQueryComplete, OnActionError, null, "SuperMap.IS.PointQueryAction");
    MapControl1.SetAction(pointQueryAction);
}

function SetLineQueryAction() {
    var layersInfo = GetQueryableFromLegend();
    var whereClause = GetWhereClause();
    lineQueryAction = new SuperMap.IS.LineQueryAction(layersInfo, null, whereClause, OnQueryComplete, OnActionError, null, "SuperMap.IS.LineQueryAction");
    MapControl1.SetAction(lineQueryAction);
}

function SetFindPathAction() {
    if (!findPathAction) {
        findPathAction = new SuperMap.IS.FindPathAction("", 0, OnFindPathComplete, OnActionError, OnFindPathStart, "SuperMap.IS.FindPathAction");
    }
    MapControl1.SetAction(findPathAction);
}

function OnFindPathStart(pe, userContext) {
    if (!pe || !pe.clientActionArgs || !pe.clientActionArgs.mapCoords) { return; }
    var points = pe.clientActionArgs.mapCoords;
    for (var i = 0; i < points.length; i++) {
        // 只有10个图标,所以只画到10.
        if (i >= 10) {
            break;
        }
        var innerHtml = "<div ondblclick='OnMarkDoubleClick();'><img src='images/icon" + (i + 1) + ".png' /></div>";
        MapControl1.CustomLayer.AddMark("FindPath_" + i, points[i].x, points[i].y, 10, 10, innerHtml, "", 10, "FindPath");
    }
}

//替换FindPath时Mark的双击事件处理函数，不进行地图缩放，进行路径分析
function OnMarkDoubleClick() {
    if (MapControl1.GetAction().type = "FindPathActionM") {
        var e = _GetEvent(e);
        _CancelBubble(e);
        e.mapCoord = MapControl1.PixelToMapCoord(e);
        findPathAction.OnDblClick(e);
    }
};

function OnFindPathComplete(routeResult) {
    if (!routeResult || !routeResult.nodeIDs || !routeResult.nodeIDs.length) { return; }
    var str = "";
    if (routeResult.totalLength > 0) {
        str += "<div style='font-size:12px'>" + resource_findPathLength + ":" + Math.round(routeResult.totalLength * 100) / 100 + "m<br>";
        if (routeResult.edgeIDs) {
            str += resource_passedEdges + ":" + routeResult.edgeIDs.length + "<br>";
        }
        if (routeResult.nodeIDs) {
            str += resource_passedNodes + ":" + routeResult.nodeIDs.length + "<br>";
        }
        str += "<div style='font-size:12px;color:blue;' onclick='ClearHighlight(); '>" + resource_clearHighlight + "</div>";
    } else {
        str += "<div style='font-size:12px'>" + resource_findPathIsNull + "<br>";
    }
    str += "</div>";
    var win = document.getElementById("menu_4_content");
    win.innerHTML = str;
    //OpenMenuBody(4, 12, true);
}



function OnQuerySuceess(resultSet,divID){
    var win = document.getElementById("menu_2_content");
    str ="<div style='background-color:#3D9BD3; height:20px;  font-size:12px'>&nbsp;&nbsp;<b>查询结果</b></div><br/>&nbsp;&nbsp;";
    if(divID=="txtqs")
    {
        str +="您的起点是：";
    }else if(divID=="txtdd"){
        str +="您的终点是：";
    }else{
    str +="您要找的是：";
    }
    
    str +="<div style='float:right'><a onclick='closeMyPlace(menu_2_content)'><img src='images/back.gif' align='absmiddle'/></a></div><br/><br/><ul id='list'>";
    var irow = 1;
    var n=1;
    var newStr;
    var myCoordsArray=new Array();

    var myCoord=new SuperMap.IS.MapCoord();
    if (!resultSet || resultSet.totalCount < 1) {
        str = "&nbsp;&nbsp;" + resource_queryResultIsNull;
    } else {
     for (var i = 0; i < resultSet.recordsets.length; i++) {
           for(var j=0;j<resultSet.recordsets[i].records.length; j++){
           var record = resultSet.recordsets[i].records[j];
           var curLayerName, layerName;
           layerName = resultSet.recordsets[i].layerName;
           var aa=MapControl1.CustomLayer;
          myCoord.x=record.center.x;
           myCoord.y=record.center.y;

         myCoordsArray.push(myCoord);
           var s=record.fieldValues[6];
            
           str +='<li class="myli"><div onclick="' + 'MapControl1.ViewByPoint(' + record.center.x + ',' + record.center.y + ');MapControl1.SetZoomLevel(5);';
           
            if(irow==11){irow=1;}
         
            str += 'MapControl1.CustomLayer.RemoveLine(\'marker\');MapControl1.CustomLayer.RemovePolygon(\'marker\');MapControl1.CustomLayer.InsertMark(\'marker\','
                + record.center.x + ',' + record.center.y + ',0,0,' + '\'<img src=\\\'img/'+ irow +'.gif\\\'';
     
            str += 'alt=\\\'' + record.fieldValues[6].replace("'", "\\\\\\\'") + '\\\' style=\\\'cursor:hand\\\' /> \');OpenNewWindow(\'' + curLayerName
                    + '\',\'' + record.fieldValues.join("$").replace("'", "\\\'") + '\',\'' + resultSet.recordsets[i].returnFields.join("$") + '\')'
                    + '">';
            if(s.length>14){ s=s.substr(0,12)+"..."};
            str +='<a style="cursor:hand" title= "'+record.fieldValues[6]+'" onclick="Setzb(' +record.center.x+ ','+record.center.y+',\''+record.fieldValues[6]+'\','+divID+')"><img src="../sxmap/img/'+irow+'.gif" align="absmiddle"/>&nbsp;&nbsp;&nbsp;&nbsp;'+s+'</a></div></li>'; 
            irow ++;
          
         }
         
       }
       str +="</ul>";
      }
     
     win.innerHTML = str ;
     showClass('list','all','p1','10');   

}
function OnQuerySuceess1(resultSet,divID){
    var record = resultSet.recordsets[0].records[0];
    var cx=record.center.x;
    var cy=record.center.y;
    var dname=record.fieldValues[6];
    if(resultSet.totalCount == 1)
    {
        if(divID=="txtqs"){
            Qszbx=cx;
            Qszby=cy;
            SqlQuery1('txtdd');
        }else 
        {
            Zdzbx=cx;
            Zdzby=cy;
            CarPath();
        }
     
    }else
    {
        OnQuerySuceess2(resultSet,divID);
    } 
}
function OnQuerySuceess2(resultSet,divID){

    var win = document.getElementById("menu_2_content");
    str ="<div style='background-color:#3D9BD3; height:20px;  font-size:12px'>&nbsp;&nbsp;<b>查询结果</b></div><br/>&nbsp;&nbsp;";
    if(divID=="txtqs")
    {
        str +="您的起点是：";
    }else if(divID=="txtdd"){
        str +="您的终点是：";
    }else{
    str +="您要找的是：";
    }
    
    str +="<div style='float:right'><a onclick='closeMyPlace(menu_2_content)'><img src='images/back.gif' align='absmiddle'/></a></div><br/><br/><ul id='list'>";
    var irow = 1;
    var n=1;
    var newStr;
    var myCoordsArray=new Array();

    var myCoord=new SuperMap.IS.MapCoord();
    if (!resultSet || resultSet.totalCount < 1) {
        str = "&nbsp;&nbsp;" + resource_queryResultIsNull;
    } else {
     for (var i = 0; i < resultSet.recordsets.length; i++) {
           for(var j=0;j<resultSet.recordsets[i].records.length; j++){
           var record = resultSet.recordsets[i].records[j];
           var curLayerName, layerName;
           layerName = resultSet.recordsets[i].layerName;
           var aa=MapControl1.CustomLayer;
          myCoord.x=record.center.x;
           myCoord.y=record.center.y;

         myCoordsArray.push(myCoord);
           var s=record.fieldValues[6];
            
           str +='<li class="myli"><div onclick="' + 'MapControl1.ViewByPoint(' + record.center.x + ',' + record.center.y + ');MapControl1.SetZoomLevel(5);';
           
            if(irow==11){irow=1;}
         
            str += 'MapControl1.CustomLayer.RemoveLine(\'marker\');MapControl1.CustomLayer.RemovePolygon(\'marker\');MapControl1.CustomLayer.InsertMark(\'marker\','
                + record.center.x + ',' + record.center.y + ',0,0,' + '\'<img src=\\\'img/'+ irow +'.gif\\\'';
     
            str += 'alt=\\\'' + record.fieldValues[6].replace("'", "\\\\\\\'") + '\\\' style=\\\'cursor:hand\\\' /> \');OpenNewWindow(\'' + curLayerName
                    + '\',\'' + record.fieldValues.join("$").replace("'", "\\\'") + '\',\'' + resultSet.recordsets[i].returnFields.join("$") + '\')'
                    + '">';
            if(s.length>14){ s=s.substr(0,12)+"..."};
            str +='<a style="cursor:hand" title= "'+record.fieldValues[6]+'"  onclick="Setsb(' +record.center.x+ ','+record.center.y+',\''+record.fieldValues[6]+'\','+divID+')"><img src="../sxmap/img/'+irow+'.gif" align="absmiddle"/>&nbsp;&nbsp;&nbsp;&nbsp;'+s+'</a></div></li>'; 
            irow ++;
          
         }
         
       }
       str +="</ul>";
      }
     
     win.innerHTML = str ;
     showClass('list','all','p1','10');   

}

//llz 设置周边查询 坐标点
function Setsb(zbx,zby,dname,txtname)
{
    if(txtname.id=="txtqs")
    {
         Qszbx=zbx;
         Qszby=zby;
         SqlQuery1('txtdd');
    }
    if(txtname.id=="txtdd")
    {
        Zdzbx=zbx;
        Zdzby=zby;
        CarPath();
    }
    var wyz = document.getElementById(txtname.id);
    wyz.value = dname;
}



//llz 设置周边查询 坐标点
function Setzb(zbx,zby,dname,txtname)
{
    Cdzbx = zbx;
    Cdzby = zby;
    if(txtname.id=="txtqs")
    {
         Qszbx=zbx;
         Qszby=zby;
          SqlQuery('txtdd');
    }
    if(txtname.id=="txtdd")
    {
        Zdzbx=zbx;
        Zdzby=zby;
         CarPath();
     }
    var wyz = document.getElementById(txtname.id);
    wyz.value = dname;
}


function ShowEntity(layerName, layerType, id) {
    MapControl1.GetEntity(MapControl1.mapName, layerName, parseInt(id), OnGetEntityComplete, OnActionError);

    function OnGetEntityComplete(entity) {
        if (entity != null && entity.shape != null) {
            var pointsX = new Array();
            var pointsY = new Array();
            for (var i = 0; i < entity.shape.points.length; i++) {
                pointsX.push(entity.shape.points[i].x);
                pointsY.push(entity.shape.points[i].y);
            }
            if (layerType == SuperMap.IS.LayerType.line) {
                MapControl1.CustomLayer.RemoveMark("marker");
                MapControl1.CustomLayer.RemovePolygon("marker");
                MapControl1.CustomLayer.InsertLine("marker", pointsX, pointsY, 2, "red", 1, null, null, null, entity.shape.parts);
            }
            if (layerType == SuperMap.IS.LayerType.polygon) {
                MapControl1.CustomLayer.RemoveMark("marker");
                MapControl1.CustomLayer.RemoveLine("marker");
                MapControl1.CustomLayer.InsertPolygon("marker", pointsX, pointsY, 2, "blue", "white", 0.6, 1, null, entity.shape.parts);
            }
            //清空一下
            while (pointsX.length > 0) {
                pointsX.pop();
                pointsY.pop();
            }
            pointsX = null;
            pointsY = null;
        }
    }
}

// 切换按钮。 Switch button//
function SwitchBtn(index, action) {
    var prefix = "btn";

    var current = "";
    var rest = "";
    former_index = 0;

    switch (action) {
        case "Over":
            if (IsBtnDown(index)) {
                break;
            }
            current = "on";
            rest = "off";
            SwitchBtnToChangeImg(current, rest, prefix, index, former_index);
            break;

        case "Out":
            if (IsBtnDown(index)) {
                break;
            }
            current = "off";
            rest = "off";
            SwitchBtnToChangeImg(current, rest, prefix, index, former_index);
            break;

        case "Down":
            for (var i = 1; i < max_btn_number; i++) {
                if (i != index) {
                    AddImgSrc(i, "img0", prefix, "off");
                }
            }

            for (var i = 10; i <= max_btn_number; i++) {
                if (i != index) {
                    AddImgSrc(i, "img", prefix, "off");
                }
            }
            current = "down";

            rest = "off";
            SwitchBtnToChangeImg(current, rest, prefix, index, former_index);
            break;
    }
}
function IsBtnDown(index) {
    var isBtnDown = false;
    if (GetImg("img" + index)) {
        var s, ss;
        s = GetImg("img" + index).src.split('.');
        ss = s[0].split('_');
        if (ss[ss.length - 1] == "down") {
            isBtnDown = true;
        }
    }
    if (GetImg("img0" + index)) {
        var s, ss;
        s = GetImg("img0" + index).src.split('.');
        ss = s[0].split('_');
        if (ss[ss.length - 1] == "down") {
            isBtnDown = true;
        }
    }
    return isBtnDown;
}

function SwitchBtnToChangeImg(current, rest, prefix, index, former_index) {
    if (former_index != index) {
        AddImgSrc(index, "img", prefix, current);
        AddImgSrc(index, "img0", prefix, current);
    } else {
        if (current != "off") {
            AddImgSrc(index, "img", prefix, current);
            AddImgSrc(index, "img0", prefix, current);
        } else {
            AddImgSrc(index, "img", prefix, "down");
            AddImgSrc(index, "img0", prefix, "down");
        }
    }
}
//添加图片链接地址
function AddImgSrc(index, imgType, prefix, current) {
    if (GetImg(imgType + index)) {
        if (imgType == "img") {
            GetImg(imgType + index).src = "images/" + prefix + "_" + index + "_" + current + ".gif";
        }
        if (imgType == "img0") {
            GetImg(imgType + index).src = "images/" + prefix + "_0" + index + "_" + current + ".gif";
        }
    }
}
function GetImg(img) {
    if (document.all) {
        return document.all(img);
    } else if (document.getElementById) { return document.getElementById(img); }
}

function OnGetBusSolutionComplete(busSolution) {
    //得到了公交换乘方案，先保存下来
    if (busSolution == null) {
        var str = "<table class='smNewForm'><tr><td>" + resource_busSolutionIsNull + "</td></tr><tr><td><input id=ReturnQueryForm4 type=button  value='"
                + resource_return + "' onclick=ReturnQueryForm()></td></tr></table>";
        var resultForm = document.getElementById("BusResultForm");
        resultForm.innerHTML = str;
        resultForm.style.display = "block";
        var queryForm = document.getElementById("BusQueryForm");
        queryForm.style.display = "none";
        return;
    }
    if (m_busSolution) {
        m_busSolution = null;
    };
    m_busSolution = new Array();
    for (var i = 0; i < busSolution.length; i++) {
        m_busSolution[i] = new SuperMap.IS.BusSolution();
        m_busSolution[i].Copy(busSolution[i]);
    }
    for (var k = 0; k < busSolution.length; k++) {
        if (busSolution[k].returnRouting == true) {
            var str;
            if (busSolution[k].routings) {
                str = "<div class='smNewForm' style='width:100%; height:150px; font-size:12px; overflow:auto'>" + resource_busSolutionLength
                        + busSolution[k].routings.length + ":";

                for (var i = 0; i < busSolution[k].routings.length; i++) {
                    str += "<div style='color:blue' onclick=\"ShowRouting(m_busSolution[" + k + "].routings[" + i + "]);\">"
                            + resource_busSolutionName + (i + 1) + ":</div>";
                    for (var j = 0; j < busSolution[k].routings[i].busLines.length; j++) {
                        var upStopID = busSolution[k].routings[i].upStops[j].smId;
                        var lineID = busSolution[k].routings[i].busLines[j].smId;
                        var downStopID = busSolution[k].routings[i].downStops[j].smId;
                        if (j == 0) {
                            if (Math.round(busSolution[k].routings[i].partsDistance[0]) > 0) {
                                str += resource_toward + AngleToDirection(busSolution[k].routings[i].partsAngle[0]) + resource_direction
                                        + Math.round(busSolution[k].routings[i].partsDistance[0]) + "m<br>";
                            }
                        }
                        str += resource_at + "<span style='color:blue' onclick='ShowBusStop(" + upStopID + ");'>"
                                + busSolution[k].routings[i].upStops[j].stopName + "</span>" + resource_getOn + ",";
                        str += resource_ride + busSolution[k].routings[i].busLines[j].lineName + resource_bus + ",";
                        str += resource_at + "<span style='color:blue' onclick='ShowBusStop(" + downStopID + ");'>"
                                + busSolution[k].routings[i].downStops[j].stopName + "</span>" + resource_getDown + ".<br>";
                        if (Math.round(busSolution[k].routings[i].partsDistance[j + 1]) > 0) {
                            str += resource_toward + AngleToDirection(busSolution[k].routings[i].partsAngle[j + 1]) + resource_direction
                                    + Math.round(busSolution[k].routings[i].partsDistance[j + 1]) + "m<br>";
                        }
                    }

                }
                str += "</div><div><input  id=ReturnQueryForm5 type=button  value='" + resource_return + "' onclick=ReturnQueryForm()></div>";
            } else {
                str = "<table class='smNewForm'><tr><td>" + resource_busSolutionIsNull + "</td></tr><tr><td><input id=ReturnQueryForm3 type=button  value='"
                        + resource_return + "' onclick=ReturnQueryForm()></td></tr></table>";
            }

            var resultForm = document.getElementById("BusResultForm");
            resultForm.innerHTML = str;
            resultForm.style.display = "block";
            var queryForm = document.getElementById("BusQueryForm");
            queryForm.style.display = "none";
        } else {
            if (!busSolution[k].startStops || !busSolution[k].endStops) {
                var str = "<table class='smNewForm'><tr><td>" + resource_busSolutionIsNull + "</td></tr><tr><td><input  id=ReturnQueryForm2 type=button  value='"
                        + resource_return + "' onclick=ReturnQueryForm()></td></tr></table>";
                var win = document.getElementById("SolutionResultWin");

                var resultForm = document.getElementById("BusResultForm");
                resultForm.innerHTML = str;
                resultForm.style.display = "block";
                var queryForm = document.getElementById("BusQueryForm");
                queryForm.style.display = "none";
                return;
            }
            //要进行站点的确认
            if (busSolution[k].startStops) {
                var strStart = "<tr><td>" + resource_selectStartStop + ":</td><td><select id=selectStartStop size=0 onclick='PanToStartStop();' >";
                for (var i = 0; i < busSolution[k].startStops.length; i++) {
                    strStart += "<option value=" + busSolution[k].startStops[i].stopId + ">" + busSolution[k].startStops[i].stopName + "("
                            + busSolution[k].startStops[i].smId + ")";
                }
                strStart += "</select></td></tr>";
            }

            if (busSolution[k].endStops) {
                var strEnd = "<tr><td>" + resource_selectEndStop + ":</td><td><select id=selectEndStop size=0 onclick='PanToEndStop();' >";
                for (var i = 0; i < busSolution[k].endStops.length; i++) {
                    strEnd += "<option value=" + busSolution[k].endStops[i].stopId + ">" + busSolution[k].endStops[i].stopName + "("
                            + busSolution[k].endStops[i].smId + ")";
                }
                strEnd += "</select></td></tr>";

            }
            //将站点都显示出来
            var x;
            var y;
            var innerHtml;
            x = busSolution[k].startStops[0].Location.x;
            y = busSolution[k].startStops[0].Location.y;
            //定位到起点
            MapControl1.ViewByPoint(x, y);
            innerHtml = "<div style='font-size:16px; color:blue; font-weight:bold'><img alt='startStop' title='startStop' src='images/marker.gif' style='cursor:hand' />"
                    + busSolution[k].startStops[0].stopName + "<div>";
            MapControl1.CustomLayer.InsertMark("startStopPosition", x, y, 10, 10, innerHtml);
            x = busSolution[k].endStops[0].Location.x;
            y = busSolution[k].endStops[0].Location.y;
            //先不定位到终点了。。。
            innerHtml = "<div style='font-size:16px; color:blue; font-weight:bold'><img alt='endStop' title='endStop' src='images/marker.gif' style='cursor:hand' />"
                    + busSolution[k].endStops[0].stopName + "<div>";
            MapControl1.CustomLayer.InsertMark("endStopPosition", x, y, 10, 10, innerHtml);

            var strDiv = "<tr><td>" + resource_passStartLines + ":</td><td>" + resource_passEndLines + ":</td></tr>" + "<tr>"
                    + "<td><span id=startLine style='left:2px;overflow:auto;width:90px;height:80px'></span></td>"
                    + "<td><span id=endLine style='left:100px;overflow;width:90px;height:80px'></span></td>" + "<tr>";
            var str = "<table class='smNewForm'>" + strStart + strEnd + "</table><table class='smNewForm'>" + strDiv
                    + "<tr><td><input id=ReturnQueryForm1 type=button  value='" + resource_return + "' onclick=ReturnQueryForm()></td><td><input id='GetBusSolution1' type=button  value="
                    + resource_query + " onclick=GetBusSolutionById()></td></tr>" + "</table>";
            var resultForm = document.getElementById("BusResultForm");
            resultForm.innerHTML = str;
            resultForm.style.display = "block";
            var queryForm = document.getElementById("BusQueryForm");
            queryForm.style.display = "none";
            //设置busSolutionStep
            busSolutionStep = true;

            //先对起点进行查询
            var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
            spatialAnalystManager.GetBusLinesByStopID(busSolution[k].startStops[0].stopId, OnGetBusLinesByStartStopIDComplete,
                    OnActionError, "GetBusLinesByStopID");
        }
    }

}
function OnShowBusStopComplete(busStop) {
}
function OnShowBusLineComplete(busLine) {
}

function OnShowRoutingComplete(busRouting) {
    if (busRouting != null) {
        var busLineNum = 0;
        var maxNum = busRouting.busLines.length;
        var upStopId;
        var downStopId;
        var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
        if (currentRouting == null || currentRouting.busLines[busLineNum] == null) {
            return;
        }
        spatialAnalystManager.GetFollowingStops(currentRouting.busLines[busLineNum].lineId, false, OnGetFollowingStopsComplete,
                OnGetFollowingStopsError, "");
    }

    function OnGetFollowingStopsComplete(e) {
        var str;
        if (currentRouting == null || currentRouting.upStops[busLineNum] == null) {
            return;
        }
        for (var i = 0; i < e.length; i++) {
            if (currentRouting.upStops[busLineNum].stopId == e[i].stopId) {
                upStopId = i;
                continue;
            }
            if (currentRouting.downStops[busLineNum].stopId == e[i].stopId) {
                downStopId = i;
                continue;
            }
        }
        if (upStopId < downStopId) {
            for (var i = 0; i <= downStopId - upStopId; i++) {
                if (e[i] == null || e[i + upStopId] == null || e[i + upStopId].Location == null) {
                    continue;
                }
                MapControl1.CustomLayer.AddMark("stopName" + e[i].stopId, e[i + upStopId].Location.x, e[i + upStopId].Location.y, 50, 10,
                        "<div style='font-size:12px; color:red; '><img src='./images/buspoint.gif'><br>" + e[i + upStopId].stopName + "</img></div>");
            }
        } else {
            for (var i = 0; i <= upStopId - downStopId; i++) {
                if (e[i] == null || e[i + upStopId] == null || e[i + upStopId].Location == null) {
                    continue;
                }
                MapControl1.CustomLayer.AddMark("stopName" + e[i].stopId, e[i + downStopId].Location.x, e[i + downStopId].Location.y, 50, 10,
                        "<div style='font-size:12px; color:red; '><img src='./images/buspoint.gif'><br>" + e[i + downStopId].stopName
                                + "</img></div>");
            }
        }

        busLineNum++;
        if (busLineNum < maxNum) {
            var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
            if (currentRouting.busLines[busLineNum] == null) {
                return;
            }
            spatialAnalystManager.GetFollowingStops(currentRouting.busLines[busLineNum].lineId, false, OnGetFollowingStopsComplete,
                    OnGetFollowingStopsError, "");
        }
    }
    function OnGetFollowingStopsError(e) { }
}


function OnGetBusLinesByStartStopIDComplete(busLines) {
    //把得到的busLines的结果放到Div里
    var startLine = document.getElementById("startLine");
    if (startLine == null) {
        //应该不会出现这种情况吧
        return;
    }
    startLine.innerHTML = "";
    if (!busLines) { return; }
    for (var i = 0; i < busLines.length; i++) {

        startLine.innerHTML += busLines[i].lineName;
        if (busLines[i].directionSign != "") {
            startLine.innerHTML += "(" + busLines[i].directionSign + ")";
        }
        startLine.innerHTML += "<br>";

    }
    if (busSolutionStep == true) {
        //还要对EndStop进行一次查询
        var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
        for (var j = 0; j < m_busSolution.length; j++) {
            spatialAnalystManager.GetBusLinesByStopID(m_busSolution[j].endStops[0].stopId, OnGetBusLinesByEndStopIDComplete,
                    OnActionError, "GetBusLinesByStopID");
        }
        busSolutionStep = false;
    }
}


function OnGetBusLinesByEndStopIDComplete(busLines) {
    //把得到的busLines的结果放到Div里
    var endLine = document.getElementById("endLine");
    if (endLine == null) {
        //应该不会出现这种情况吧
        return;
    }
    endLine.innerHTML = "";
    if (!busLines) { return; }
    for (var i = 0; i < busLines.length; i++) {

        endLine.innerHTML += busLines[i].lineName;
        if (busLines[i].directionSign != "") {
            endLine.innerHTML += "(" + busLines[i].directionSign + ")";
        }
        endLine.innerHTML += "<br>"

    }

}


function GetBusSolution() {
    var busSolutionParam = new SuperMap.IS.BusSolutionParam();
    busSolutionParam.transferTimes = 2;
    busSolutionParam.most = true;
    busSolutionParam.expected = 2;
    busSolutionParam.orderMode = SuperMap.IS.BusSolutionOrderMode.byDistance;

    var coordmode = document.getElementById("MapCoordMode");
    if (coordmode.checked == true) {
        GetBusSolutionByPoint(busSolutionParam);
        return;
    }
    GetBusSolutionByName(busSolutionParam);
}

function GetBusSolutionByPoint(busSolutionParam) {
    var strBusStart = document.getElementById("startStop").value;
    var strBusEnd = document.getElementById("endStop").value;
    var start = strBusStart.split(',');
    var end = strBusEnd.split(',');
    var points = new Array();
    points[0] = new SuperMap.IS.MapCoord(parseFloat(start[0]), parseFloat(start[1]));
    points[1] = new SuperMap.IS.MapCoord(parseFloat(end[0]), parseFloat(end[1]));

    document.getElementById("startStop").value = "";
    document.getElementById("endStop").value = "";
    SetPanAction();

    var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
    spatialAnalystManager.GetBusSolutionByPoints(points, 200, busSolutionParam, OnGetBusSolutionComplete, OnActionError, "GetBusSolutionByPoints");
}

function GetBusSolutionByName(busSolutionParam) {
    var startStop = document.getElementById("startStop").value;
    var endStop = document.getElementById("endStop").value;
    var name = new Array();
    name.push(startStop, endStop);
    if (!startStop || typeof (startStop) != "string") {
        alert(resource_inputStartStop);
        return;
    }
    if (!endStop || typeof (endStop) != "string") {
        alert(resource_inputEndStop);
        return;
    }
    var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
    spatialAnalystManager.GetBusSolutionByNames(name, busSolutionParam, OnGetBusSolutionComplete, OnActionError, "GetBusSolutionByNames");
}

function GetBusSolutionById() {
    //清除选择站点时起始站点和终止站点的高亮
    MapControl1.CustomLayer.RemoveMark("startStopPosition");
    MapControl1.CustomLayer.RemoveMark("endStopPosition");
    var selectStartStop = document.getElementById("selectStartStop").value;
    var selectEndStop = document.getElementById("selectEndStop").value;
    SetPanAction();
    var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
    var ids = new Array(parseInt(selectStartStop), parseInt(selectEndStop));
    var busSolutionParam = new SuperMap.IS.BusSolutionParam();
    busSolutionParam.transferTimes = 2;
    busSolutionParam.most = true;
    busSolutionParam.expected = 2;
    busSolutionParam.orderMode = SuperMap.IS.BusSolutionOrderMode.byDistance;
    spatialAnalystManager.GetBusSolutionByIds(ids, busSolutionParam, OnGetBusSolutionComplete, OnActionError, "GetBusSolutionByIds");
}

function ShowBusStop(id) {
    if (MapControl1.mapName != 'changchun') {
        return;
    }
    if (!id) {
        alert(resource_inputStopId);
        return;
    }
    //var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
    MapControl1.ShowBusStop(id, null, OnShowBusStopComplete, OnActionError, "ShowBusStop");
}

function ShowBusLine(id) {
    if (MapControl1.mapName != 'changchun') {
        return;
    }
    if (!id) {
        alert(resource_inputLindId);
        return;
    }
    //var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
    MapControl1.ShowBusLine(id, null, OnShowBusLineComplete, OnActionError, "ShowBusLine");
}

function ShowRouting(busRouting) {
    if (MapControl1.mapName != 'changchun') {
        return;
    }
    if (!busRouting) {
        alert(resource_inputBusRouting);
        return;
    }
    //var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
    MapControl1.ShowRouting(busRouting, OnShowRoutingComplete, OnActionError, "ShowRouting");
    currentRouting = busRouting;
}

function PanToStartStop() {
    //2006-9-12 对于用户来说，给出换乘点ID是没有意义的，给出换乘点的线路信息
    var selectStartStop = document.getElementById("selectStartStop");
    var x = m_busSolution[0].startStops[selectStartStop.selectedIndex].Location.x;
    var y = m_busSolution[0].startStops[selectStartStop.selectedIndex].Location.y;
    MapControl1.ViewByPoint(x, y);
    var innerHtml = "<div style='font-size:16px; color:blue; font-weight:bold'><img alt='startStop' src='images/marker.gif' style='cursor:hand' />"
            + m_busSolution[0].startStops[selectStartStop.selectedIndex].stopName + "<div>";
    MapControl1.CustomLayer.InsertMark("startStopPosition", x, y, 10, 10, innerHtml);
    var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
    //spatialAnalystManager.RegisterHandler(OnGetBusLinesByStartStopIDComplete, onGetBusLinesByStartStopIDError);
    spatialAnalystManager.GetBusLinesByStopID(m_busSolution[0].startStops[selectStartStop.selectedIndex].stopId, OnGetBusLinesByStartStopIDComplete,
            OnActionError, "GetBusLinesByStopID");

}
function PanToEndStop() {
    //2006-9-12 对于用户来说，给出换乘点ID是没有意义的，给出换乘点的线路信息
    var selectEndStop = document.getElementById("selectEndStop");
    var x = m_busSolution[0].endStops[selectEndStop.selectedIndex].Location.x;
    var y = m_busSolution[0].endStops[selectEndStop.selectedIndex].Location.y;
    MapControl1.ViewByPoint(x, y);
    var innerHtml = "<div style='font-size:16px; color:blue; font-weight:bold'><img alt='endStop' src='images/marker.gif' style='cursor:hand' />"
            + m_busSolution[0].endStops[selectEndStop.selectedIndex].stopName + "<div>";
    MapControl1.CustomLayer.InsertMark("endStopPosition", x, y, 10, 10, innerHtml);
    var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
    spatialAnalystManager.GetBusLinesByStopID(m_busSolution[0].endStops[selectEndStop.selectedIndex].stopId, OnGetBusLinesByEndStopIDComplete,
            OnActionError, "GetBusLinesByStopID");
}

function SetMeasureDistanceAction() {
    if (!measureDistanceAction) {
        measureDistanceAction = new SuperMap.IS.MeasureDistanceAction(OnMeasureComplete, OnActionError, null, "SuperMap.IS.MeasureDistanceAction");
        //	    measureDistanceAction = new NewMeasureDistanceAction (OnMeasureDistanceComplete ,onMeasureDistanceError );
    }
    MapControl1.SetAction(measureDistanceAction);
}

function SetMeasureAreaAction() {
    //alert("dsdfds");
    if (!measureAreaAction) {
        measureAreaAction = new SuperMap.IS.MeasureAreaAction(OnMeasureComplete, OnActionError, null, "SuperMap.IS.MeasureAreaAction");
        //	    measureAreaAction = new NewMeasureAreaAction(OnMeasureAreaComplete ,onMeasureAreaError );
    }
    MapControl1.SetAction(measureAreaAction);
}

function OnMeasureComplete(result, userContext) {
    var str = "";
    if (result) {
        if (userContext == "SuperMap.IS.MeasureAreaAction") {
            str += "<div style='font-size:12px'>" + resource_measureAreaLength + ":<br>" + Math.round(result.area * 100) / 100 + resource_squareMeter + "<br>";
        }
        else {
            str += "<div style='font-size:12px'>" + resource_measureDistanceLength + ":<br>" + Math.round(result.distance * 100) / 100 + resource_meter + "<br>";
        }
    } else {
        str += "<div style='font-size:12px'>" + resource_measureResultIsNull + "<br>";
    }
    str += "<div style='font-size:12px;color:blue;' onclick='MapControl1.ClearHighlight() '>" + resource_clearHighlight + "</div>";
    str += "</div>";
    var win = document.getElementById("menu_3_content");
    win.innerHTML = str;
    //OpenMenuBody(3, 12, true);
}

function ClearHighlight() {
    MapControl1.ClearHighlight();
    MapControl1.CustomLayer.ClearMarks();
    MapControl1.CustomLayer.ClearLines();
    MapControl1.CustomLayer.ClearPolygons();
    currentRouting = null;
}


//function SetRectQueryAction() {
//    var layersInfo = GetQueryableFromLegend();
//    var whereClause = GetWhereClause();
//    rectQueryAction = new SuperMap.IS.RectQueryAction(layersInfo, null, whereClause, OnQurye1, OnActionError, null, "SuperMap.IS.RectQueryAction");
//    MapControl1.SetAction(rectQueryAction);
//}
function SetRectQueryAction() {
    var layersInfo = new Array("MapIndexRN1W@SXWebMeta");
    var whereClause = "smid > 0"
    rectQueryAction = new SuperMap.IS.RectQueryAction(layersInfo, null, whereClause, OnQurye1, OnActionError, null, "SuperMap.IS.RectQueryAction");
    MapControl1.SetAction(rectQueryAction);
}

function RectQueryAction()
{
//QueryByRect
}

function OnQueryComplete2(resultSet) {
    var str = "<div style='padding-bottom: 5px;max-height:400px;overflow-y:scroll' ><table id='table1' border='0'><tbody id='group_one'>";
    if (!resultSet || resultSet.totalCount < 1) {
        str = "&nbsp;&nbsp;" + resource_queryResultIsNull;
    } else {
    var irow = 1;
        for (var i = 0; i < resultSet.recordsets.length; i++) 
        {
            // 使用 layerId 不是很保险，因为查询时所使用的 layers，和当前的 layers，不一定就完全一致。
            // 应当使用 layerName。  --ahnan 2008-08-13
            var layerType = 0;

                    layerType = SuperMap.IS.LayerType.point;//MapControl1.layers[j].type;

            for (var j = 0; j < resultSet.recordsets[i].records.length; j++) 
            {
                var record = resultSet.recordsets[i].records[j];
                var curLayerName, layerName;
                layerName = resultSet.recordsets[i].layerName;

                str += '<tr><td><a>'+irow+'</a></td><td><div id="QueryResult' + curLayerName + record.fieldValues[6]
                        + '" style="border-bottom:dotted 1px black;" class="query" onclick="' + 'window.curMapControl.ViewByPoint(' + record.center.x
                        + ',' + record.center.y + ');';//这里应该是高亮显示
                switch (layerType) 
                {//是点类型的才操作
                    case SuperMap.IS.LayerType.point:
                        str += 'window.curMapControl.CustomLayer.RemoveLine(\'marker\');window.curMapControl.CustomLayer.RemovePolygon(\'marker\');window.curMapControl.CustomLayer.InsertMark(\'marker\','
                                + record.center.x + ',' + record.center.y + ',10,10,' + '\'<img src=\\\'images/marker.gif\\\'';
                        var m;
                            str += 'alt=\\\'' + record.fieldValues[6].replace("'", "\\\\\\\'") + '\\\' style=\\\'cursor:hand\\\' /> \');OpenNewWindow(\'' + curLayerName
                                    + '\',\'' + record.fieldValues.join("$").replace("'", "\\\'") + '\',\'' + resultSet.recordsets[i].returnFields.join("$") + '\')'
                                    + '">';
                        irow=irow+1;
                        break;
                    case SuperMap.IS.LayerType.line:
                    case SuperMap.IS.LayerType.polygon:
                    default:
                        str += 'ShowEntity(\'' + layerName + '\',' + layerType + ',\'' + record.fieldValues[0] + '\');OpenNewWindow(\''
                                + curLayerName + '\',\'' + record.fieldValues.join("$").replace("'", "\\\'") + '\',\'' + resultSet.recordsets[i].returnFields.join("$")
                                + '\')' + '">';
                        break;
                }

                            //str += '<a href=#>'+record.fieldValues[5]+'</a>';Setzb(' +record.center.x+ ','+record.center.y+',\''+record.fieldValues[5]+'\')
                            str += '<a href=javascript:setPlace(\''+record.fieldValues[6]+'\',\'txtwyz\',\'myPlace\');Setzb('+record.center.x+','+record.center.y+',\''+record.fieldValues[6]+'\')>'+record.fieldValues[6]+'</a>';
                            str += '</div></td></tr>';
                            useDefault = false;
            }
        }

    }
    str += "</tbody></table></div>";
    var win = document.getElementById("myPlace");
    win.innerHTML = str;
    //OpenMenuBody(2, 12, true);
}



//路径分析前查询结果 如何给回调函数传值
function OnQueryComplete3(resultSet) {
    var str = "<div style='padding-bottom: 5px;overflow:auto' ><table id='table3' border='0'><tbody id='group_one'>";
    if (!resultSet || resultSet.totalCount < 1) {
        str = "&nbsp;&nbsp;" + resource_queryResultIsNull;
    } else {
    var irow = 1;
        for (var i = 0; i < resultSet.recordsets.length; i++) 
        {
            // 使用 layerId 不是很保险，因为查询时所使用的 layers，和当前的 layers，不一定就完全一致。
            // 应当使用 layerName。  --ahnan 2008-08-13
            var layerType = 0;

                    layerType = SuperMap.IS.LayerType.point;//MapControl1.layers[j].type;

            for (var j = 0; j < resultSet.recordsets[i].records.length; j++) 
            {
                var record = resultSet.recordsets[i].records[j];
                var curLayerName, layerName;
                layerName = resultSet.recordsets[i].layerName;

                str += '<tr><td><a>'+irow+'</a></td><td><div id="QueryResult' + curLayerName + record.fieldValues[6]
                        + '" style="border-bottom:dotted 1px black;" class="query" onclick="' + 'window.curMapControl.ViewByPoint(' + record.center.x
                        + ',' + record.center.y + ');';//这里应该是高亮显示
                switch (layerType) 
                {//是点类型的才操作
                    case SuperMap.IS.LayerType.point:
                        str += 'window.curMapControl.CustomLayer.RemoveLine(\'marker\');window.curMapControl.CustomLayer.RemovePolygon(\'marker\');window.curMapControl.CustomLayer.InsertMark(\'marker\','
                                + record.center.x + ',' + record.center.y + ',10,10,' + '\'<img src=\\\'images/marker.gif\\\'';
                        var m;
                            str += 'alt=\\\'' + record.fieldValues[6].replace("'", "\\\\\\\'") + '\\\' style=\\\'cursor:hand\\\' /> \');OpenNewWindow(\'' + curLayerName
                                    + '\',\'' + record.fieldValues.join("$").replace("'", "\\\'") + '\',\'' + resultSet.recordsets[i].returnFields.join("$") + '\')'
                                    + '">';
                        irow=irow+1;
                        break;
                    case SuperMap.IS.LayerType.line:
                    case SuperMap.IS.LayerType.polygon:
                    default:
                        str += 'ShowEntity(\'' + layerName + '\',' + layerType + ',\'' + record.fieldValues[0] + '\');OpenNewWindow(\''
                                + curLayerName + '\',\'' + record.fieldValues.join("$").replace("'", "\\\'") + '\',\'' + resultSet.recordsets[i].returnFields.join("$")
                                + '\')' + '">';
                        break;
                }
                                                          //Setzb(' +record.center.x+ ','+record.center.y+',\''+record.fieldValues[5]+'\')
                            str += '<a href=javascript:settxt(\''+record.fieldValues[6]+'\',\'txtqs\');SetQS('+record.center.x+','+record.center.y+',\''+record.fieldValues[6]+'\')>'+record.fieldValues[6]+'</a>';
                            str += '</div></td></tr>';
                            useDefault = false;
            }
        }

    }
    str += "</tbody></table></div>";
    var win = document.getElementById("qsjg");
    win.innerHTML = str;
}

function OnQueryComplete4(resultSet) {
    var str = "<div style='padding-bottom: 5px;overflow:auto' ><table id='table4' border='0'><tbody id='group_one'>";
    if (!resultSet || resultSet.totalCount < 1) {
        str = "&nbsp;&nbsp;" + resource_queryResultIsNull;
    } else {
    var irow = 1;
        for (var i = 0; i < resultSet.recordsets.length; i++) 
        {
            // 使用 layerId 不是很保险，因为查询时所使用的 layers，和当前的 layers，不一定就完全一致。
            // 应当使用 layerName。  --ahnan 2008-08-13
            var layerType = 0;

                    layerType = SuperMap.IS.LayerType.point;//MapControl1.layers[j].type;

            for (var j = 0; j < resultSet.recordsets[i].records.length; j++) 
            {
                var record = resultSet.recordsets[i].records[j];
                var curLayerName, layerName;
                layerName = resultSet.recordsets[i].layerName;

                str += '<tr><td><a>'+irow+'</a></td><td><div id="QueryResult' + curLayerName + record.fieldValues[6]
                        + '" style="border-bottom:dotted 1px black;" class="query" onclick="' + 'window.curMapControl.ViewByPoint(' + record.center.x
                        + ',' + record.center.y + ');';//这里应该是高亮显示
                switch (layerType) 
                {//是点类型的才操作
                    case SuperMap.IS.LayerType.point:
                        str += 'window.curMapControl.CustomLayer.RemoveLine(\'marker\');window.curMapControl.CustomLayer.RemovePolygon(\'marker\');window.curMapControl.CustomLayer.InsertMark(\'marker\','
                                + record.center.x + ',' + record.center.y + ',10,10,' + '\'<img src=\\\'images/marker.gif\\\'';
                        var m;
                            str += 'alt=\\\'' + record.fieldValues[6].replace("'", "\\\\\\\'") + '\\\' style=\\\'cursor:hand\\\' /> \');OpenNewWindow(\'' + curLayerName
                                    + '\',\'' + record.fieldValues.join("$").replace("'", "\\\'") + '\',\'' + resultSet.recordsets[i].returnFields.join("$") + '\')'
                                    + '">';
                        irow=irow+1;
                        break;
                    case SuperMap.IS.LayerType.line:
                    case SuperMap.IS.LayerType.polygon:
                    default:
                        str += 'ShowEntity(\'' + layerName + '\',' + layerType + ',\'' + record.fieldValues[0] + '\');OpenNewWindow(\''
                                + curLayerName + '\',\'' + record.fieldValues.join("$").replace("'", "\\\'") + '\',\'' + resultSet.recordsets[i].returnFields.join("$")
                                + '\')' + '">';
                        break;
                }
                            str += '<a href=javascript:settxt(\''+record.fieldValues[6]+'\',\'txtdd\');SetZD('+record.center.x+','+record.center.y+',\''+record.fieldValues[6]+'\')>'+record.fieldValues[6]+'</a>';
                            str += '</div></td></tr>';
                            useDefault = false;
            }
        }

    }
    str += "</tbody></table></div>";
    var win = document.getElementById("zdjg");
    win.innerHTML = str;
}

function SqlQuery4() {
    var doc = document;
    //alert("dfds");
    var select = doc.getElementById("txtdd").value;
    if(select==null || select=="")
    {
        alert("没有输入查询名称，请输入要查询的地方名称或名称关键字！");
        return;
    }
    var queryParam = new SuperMap.IS.QueryParam();
    queryParam.IsAllLayer = false; // 设置查询模式为不查询所有图层

    queryParam.queryLayers = new Array(26);
    //
    var tName = tables.split(',');
    for(var i=0;i<tName.length;i++)
    {
    var queryLayer2 = new SuperMap.IS.QueryLayer();
    queryLayer2.whereClause = " NAME like '%"+select+"%' ";
    queryLayer2.layerName = tName[i];
    queryParam.queryLayers[i] = queryLayer2;
    }
    queryParam.expectCount = parseInt("10000");
    var queryManager = MapControl1.GetQueryManager();
    var resultSet = queryManager.QueryBySql(queryParam, OnQueryComplete4, OnActionError);
    select = null;
}
//llz 下面两个方法是设置路径分析的起始和终点坐标
function SetQS(zbx,zby,str)
{
    Qszbx=zbx;
    Qszby=zby;
    var wyz = document.getElementById("txtqs");
    wyz.value = str;
}
function SetZD(zbx,zby,str)
{
    Zdzbx=zbx;
    Zdzby=zby;
    var wyz = document.getElementById("txtdd");
    wyz.value = str;
}

//数据订阅
function OnQurye1(result)
{
debugger;
    //var str = '';
    TcUrl = '';//重置
    if(result.currentCount>0)
    {
        for (var i = 0; i < result.recordsets.length; i++) 
        {
            for (var j = 0; j < result.recordsets[i].records.length; j++) 
            {
                var record = result.recordsets[i].records[j];
                TcUrl += (record.fieldValues[0]);
                
                if (j != (result.recordsets[i].records.length) - 1)
                {
                    TcUrl += ',';
                }
                
            }
        }
       }else
       {
            alert("您选择的区域超出范围！请重新选择");
       }
}
function TiJiaoXX()
{
    var winminx = document.getElementById("txtminx");
    var winminy = document.getElementById("txtminy");
    var winmaxx = document.getElementById("txtmaxx");
    var winmaxy = document.getElementById("txtmaxy");

    var strzb=winminx.value+","+winminy.value+","+winmaxx.value+","+winmaxy.value;
    window.location.href="./orderOnline/OrderList.aspx?resutlt="+TcUrl+"&fw="+strzb;
}

//llz
function piontquery(divids)
{
debugger;
    var mapCoords = new SuperMap.IS.MapCoord();
    var cznr = document.getElementById("txtfjz").value;
    if(cznr == null || cznr == "" )
    {
        alert("没有输入查询名称，请输入要查询的地方名称或名称关键字！");
        return;
    }
    if(Cdzbx=="" || Cdzby ==null)
    {
        alert("没有选择附近地点，请选择可能的范围的附近标识性地点！");
        return;
    }
    var jlfw = document.getElementById("Selectfj");
    var jlfw1 = jlfw.options[jlfw.selectedIndex].value;
    jlfw1=jlfw.options.value;
    mapCoords.y=Cdzby;//3328085.9596610404;
    mapCoords.x=Cdzbx;//542295.9743734613;
    var bj=ConvertJL(jlfw1);//10000;
    var queryParam = new SuperMap.IS.QueryParam();
    queryParam.queryLayers = new Array(1);
    queryParam.highlight = new SuperMap.IS.Highlight();
    
    queryParam.highlight.highlightQueryArea = true;
    queryParam.highlight.queryAreaStyle = new SuperMap.IS.Style();
    queryParam.highlight.queryAreaStyle.brushOpaqueRate = 0;
    queryParam.highlight.queryAreaStyle.penColor = 2;
    queryParam.highlight.queryAreaStyle.penStyle = 2;
    queryParam.IsAllLayer = false; // 设置查询模式为不查询所有图层
    var queryLayer = new SuperMap.IS.QueryLayer();

    queryParam.queryLayers[0] = queryLayer;
    queryParam.expectCount = 1000;
   

        var queryLayer2 = new SuperMap.IS.QueryLayer();
        queryLayer2.whereClause = " NAME like '%"+cznr+"%' ";
        queryLayer2.layerName = tables;
        queryParam.queryLayers[0] = queryLayer2;
        
    var queryManager = MapControl1.GetQueryManager();
    var resultSet = queryManager.QueryByPoint(mapCoords,bj,queryParam, OnQuerySuceess, OnActionError,divids);
}
//llz
function ConvertJL(selectedvalues)
{
     switch (selectedvalues) 
     {
        case "1公里":
            return 1000
        case "2公里":
            return 2000;
        case "5公里":
            return 5000;
        case "10公里":
            return 10000;
        case "15公里":
            return 15000;
        case "20公里":
            return 20000;
        default:
            return 0;
    }
}

//llz
function Findpaths(qsid)
{
   carQuery(qsid);
}
function CarPath()
{
    var routParams = new SuperMap.IS.RouteParam();
    var networkParams = new SuperMap.IS.NetworkParams();
    var networksets =new SuperMap.IS.NetworkSetting();
    var returninfos = new SuperMap.IS.ReturnPathInfoParam();
    networksets.networkLayerNames = "RoadNet@SXWebMeta";
    networkParams.networkSetting=networksets;
    var ids= new Array();
    var mapCoords = new SuperMap.IS.MapCoord();
    mapCoords.y= Qszby;//3328085.9596610404;
    mapCoords.x= Qszbx;//542295.9743734613;
    var mapCoords2 = new SuperMap.IS.MapCoord();
    mapCoords2.y= Zdzby;//3321106.9596610404;
    mapCoords2.x= Zdzbx;//566678.9743734613;
    ids[0]=mapCoords;
    ids[1]=mapCoords2;
    routParams.networkParams=networkParams;
    var higL = new SuperMap.IS.Highlight();
    higL.highlight = true;
    higL.returnCosts = true;
    higL.retunEdgeIDsAndNodeIDs=true;
    higL.returnNodePositions=true;
    higL.returnPathInfo=true;
    routParams.highlight=higL;
    routParams.returnCosts=true;//是否返回路径耗费信息
    routParams.returnPathInfo=returninfos;//是否返回包含路径信息的表
    returninfos.edgeNameField="name";//字段名称
    returninfos.returnPathGuide=true;//是否返回行驶导引信息
    returninfos.returnPathTable=true;//是否返路径信息表
    routParams.returnNodePositions=true;//是否返回节点位置信息
    var queryAnalManager = MapControl1.GetSpatialAnalystManager();
    var resultSet = queryAnalManager.FindPathByPoints(ids,routParams, Findpathjg, Findpathsb);
}
function waiting()
{
    var waitDiv=document.getElementById("menu_2_content");
    waitDiv.innerHTML="<div ><img src='images/map/20.gif'/> <span style='color:red;font-size:12px;'>正在读取数据，请稍等...</span></div>";
}

function Findpathjg(routeResult)
{
//alert("chenggong");
document.getElementById("p1").style.display="none";
            var str = "";
            if (!routeResult || routeResult.totalLength == 0) 
            {
                str = " 提示：" ;
            } 
            else 
            {
                if (!routeResult.pathGuides) 
                {
                    str = ("没有返回路径引导信息！");
                }
                else 
                {
                    // 将分析返回的路径引导信息显示出来
                    var pathGuides = routeResult.pathGuides;
                    for (var m = 0; m < pathGuides.length; m++) 
                    {
                        var pathGuide = pathGuides[m];
                        str = " <table class='qMyList'  border='1' cellspacing='0' cellpadding='0'>";
                        str += " ";
                        var StopIndex = 0;
                        var turnIndex = 0;
                        var ibh = 1;//序号
                        for (var i = 0; i < pathGuide.count; i++) 
                        {
                            var pathGuideItem = pathGuide.pathGuideItems[i];
                            if (pathGuideItem.isStop) //判断是否为站点（起始或终点）
                            {
                                turnIndex++;
                                continue;
                            }
                            if (pathGuideItem.isEdge) //判断是否是弧段
                            {
                                str += "<tr><td><b>"
                                        + ibh
                                        + "</b></td><td>"
                                if(ibh==1)
                                    str +="从起始点出发,"
                                str += "沿";
                                if (pathGuideItem.name == "" || pathGuideItem.name == null || pathGuideItem.name == "Anonymous")
                                    str += " 匿名路段 ";
                                else
                                    str += " " + pathGuideItem.name + " ";
                                if (pathGuideItem.directionType == 0)
                                    str += ",向东";
                                if (pathGuideItem.directionType == 1)
                                    str += ",向南";
                                if (pathGuideItem.directionType == 2)
                                    str += ",向西";
                                if (pathGuideItem.directionType == 3)
                                    str += ",向北";
                                str += "行走 " + jsLength(pathGuideItem.length);
                            }
                            if (!pathGuideItem.isStop && !pathGuideItem.isEdge) //即不是站点也不是弧段
                            {
                                turnIndex++;
                                continue;
                            }

                            str += "</td>";
                            ibh++;
                        }
                        str += "</table>";
                    }
                }
            }
            var win = document.getElementById("menu_2_content");
            //win不为空，将查询结果显示出来
            win.innerHTML = str;

//var zcd=routeResult.tolalLength;//总路长度（单位：米）
}
//llz
function jsLength(jlz)
{
    var str ="";
    if(parseFloat(jlz)<1000)
    {
        str=parseInt(jlz)+"米";
    }
    else
    {
       var glz=jlz/1000.0;
       str=Math.round(glz)+"千米";
    }
    return str;
}
//llz
function CoverDirections(fxtype,zwtype,zwAngle)
{
    var str = "";
        switch (true)
        {
            case (angle > 337.5 || angle <= 22.5):
                str = "向东";
                break;
            case (angle > 22.5 && angle <= 67.5):
                str = "向东北";
                break;
            case (angle > 67.5 && angle <= 112.5):
                str = "向北";
                break;
            case (angle > 112.5 && angle <= 157.5):
                str = "向西北";
                break;
            case (angle > 157.5 && angle <= 202.5):
                str = "向西";
                break;
            case (angle > 202.5 && angle <= 247.5):
                str = "向西南";
                break;
            case (angle > 247.5 && angle <= 292.5):
                str = "向南";
                break;
            case (angle > 292.5 && angle <= 337.5):
                str = "向东南";
                break;
        }
    return str;//返回向哪个方向走
}
function PrintMap()
{
    //myMap.GetMapImage(myMap.GetMapParam(),onGetMapImageComplete,onError);
    window.print();
}
function Print()
{
	if(window.confirm("确定打印?"))
	{
		window.print();
	}
}

function EnterPress(e,ids)
{
    var Enkey = e || window.event;
    if(Enkey.keyCode == 13)
    {
        switch (ids)
        {
            case "txtcznr":
                showMyPlace('menu_2_content');
                SqlQuery(ids);
                break;
            case "txtwyz":
                alert("周边查找");
                break;
            case "txtfjz":
                piontquery('menu_2_content');
                showMyPlace('menu_2_content');
                break;
            default:
                break;
        }
    }
}

function Findpathsb(resultSet)
{
alert("查询失败！");
}

function ReturnQueryForm() {
    var resultForm = document.getElementById("BusResultForm");
    resultForm.style.display = "none";
    var queryForm = document.getElementById("BusQueryForm");
    queryForm.style.display = "block";
    var coordmode = document.getElementById("MapCoordMode");
    if (coordmode.checked) {
        SetGetCoordsAction(2);
    }
    var startStop = document.getElementById("startStop");
    startStop.focus();
}

//打开菜单内容 不用打开了llz
function OpenMenuBody(num, total, open) 
{
    var doc = document;
    for (var i = 1; i < total + 1; i++) 
    {
        var menuContentId = "menu_" + i + "_content";
        var menuButtonId = "menu_" + i + "_button";
        var menuContent = doc.getElementById(menuContentId);
        var menuButton = doc.getElementById(menuButtonId);
        if (i == num) 
        {
            if (menuContent.style.display == "none" || menuContent.style.display == "") 
            {
                menuContent.style.display = "block";
                ChageButtonImg(menuButton, "open");
            } 
            else 
            {
                if (!open) 
                {
                    menuContent.style.display = "none";
                    ChageButtonImg(menuButton);
                }
            }
        } 
        else 
        {
            menuContent.style.display = "none";
            ChageButtonImg(menuButton);
        }
    }
}

//切换菜单都得按钮图片
function ChageButtonImg(obj, str) {
    if (str == "open") {
        obj.style.backgroundImage = "url('./images/open.gif')";
    } else {
        obj.style.backgroundImage = "url('./images/closemenu.gif')";
    }
}

function ReSizeDiv() {
    var doc = document;
    var menu = doc.getElementById("menus");
    var imgButton = doc.getElementById("menu_button");
    var mapTitle = doc.getElementById("title_map");
    var offsetDistanst = menu.offsetWidth
    var mapContent = doc.getElementById("map_content");
    var mapBody = doc.getElementById("myMap");
    var tool = doc.getElementById("tool");
    var mapControl = doc.getElementById("MapControl1");
    var menuLeft = menu.offsetLeft;
    var magnifierControl = doc.getElementById("MagnifierControl1");
    var pcX = MapControl1.GetPixelCenterX();
    var pcY = MapControl1.GetPixelCenterY();
    var borderWidth = parseInt(mapControl.style.borderWidth.split("px")[0]);

    if (menuLeft < 0) {
        menu.style.left = 0 + "px";
        imgButton.style.left = offsetDistanst + "px";
        mapTitle.style.left = mapTitle.offsetLeft + offsetDistanst + "px";
        magnifierControl.style.left = magnifierControl.offsetLeft - offsetDistanst + "px";
        mapContent.style.width = mapContent.offsetWidth - offsetDistanst + "px";
        mapBody.style.width = mapBody.offsetWidth - offsetDistanst + "px";
        tool.style.width = tool.offsetWidth - offsetDistanst + "px";
        pcX -= offsetDistanst / 2;
        MapControl1.Resize(mapControl.offsetWidth - borderWidth * 2 - offsetDistanst, mapControl.offsetHeight - borderWidth * 2);
    } else {
        menu.style.left = -offsetDistanst + "px";
        imgButton.style.left = 0 + "px";
        mapTitle.style.left = mapTitle.offsetLeft - offsetDistanst + "px";
        mapContent.style.width = mapContent.offsetWidth + offsetDistanst + "px";
        magnifierControl.style.left = magnifierControl.offsetLeft + offsetDistanst + "px";
        mapBody.style.width = mapBody.offsetWidth + offsetDistanst + "px";
        tool.style.width = tool.offsetWidth + offsetDistanst + "px";
        pcX += offsetDistanst / 2;
        MapControl1.Resize(mapControl.offsetWidth - borderWidth * 2 + offsetDistanst, mapControl.offsetHeight - borderWidth * 2);
    }
    MapControl1.SetCenterAndZoom(pcX, pcY, MapControl1.GetMapScale());
}


function StartDynamicNavigate() {
    MapControl1.StopDynamicNavigate();

    var busLineEntity = new Array();
    var busLineNum = 0;
    var maxPointNum = 0;
    var viewBounds = MapControl1.GetViewBounds();
    var center = viewBounds.Center();
    var width = viewBounds.Width() / 4;
    var height = viewBounds.Height() / 4;
    var points = new Array();
    var pointsName = new Array();
    if (currentRouting) {
        var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
        MapControl1.GetEntity(MapControl1.mapName, "BusLine@changchun", currentRouting.busLines[0].smId, OnGetComplete, OnError);
        return;
    } else {
        points[0] = new SuperMap.IS.MapCoord(center.x - width, center.y + height);
        points[1] = new SuperMap.IS.MapCoord(center.x - width, center.y - height);
        points[2] = new SuperMap.IS.MapCoord(center.x + width, center.y - height);
        points[3] = new SuperMap.IS.MapCoord(center.x + width, center.y + height);
        points[4] = new SuperMap.IS.MapCoord(center.x - width, center.y + height);
    }
    var areas = new Array();
    areas[0] = new SuperMap.IS.MapRect(viewBounds.leftBottom.x + width, viewBounds.leftBottom.y - height, viewBounds.rightTop.x + width,
            viewBounds.rightTop.y - height);
    bPasueDynamicNavigate = false;
    var step = width < height ? width / 10 : height / 10;
    MapControl1.StartDynamicNavigate(points, areas, "images/walk8.gif", "images/walk2.gif", null, null, true, step, 100, null, "");

    function OnGetComplete(entity) {
        if (entity != null) {
            for (var i = 0; i < entity.shape.points.length; i++) {
                busLineEntity[i] = entity.shape.points[i];
            }
            var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
            var stopIds = new Array();
            stopIds[0] = currentRouting.upStops[busLineNum].smId;
            stopIds[1] = currentRouting.downStops[busLineNum].smId;
            MapControl1.GetEntities(MapControl1.mapName, "BusPoint@changchun", stopIds, OnGetStopsComplete, OnError, busLineEntity);
        }
    }

    function OnGetStopsComplete(stopsEntities) {
        var upStopId, downStopId, upDistance, downDistance, tempDistance;
        if (currentRouting.upStops[busLineNum].smId == parseInt(stopsEntities[0].fieldValues[0])) {
            var upStopCoord = new SuperMap.IS.MapCoord(stopsEntities[0].shape.points[0].x, stopsEntities[0].shape.points[0].y);
            var downStopCoord = new SuperMap.IS.MapCoord(stopsEntities[1].shape.points[0].x, stopsEntities[1].shape.points[0].y);
        } else {
            var upStopCoord = new SuperMap.IS.MapCoord(stopsEntities[1].shape.points[0].x, stopsEntities[1].shape.points[0].y);
            var downStopCoord = new SuperMap.IS.MapCoord(stopsEntities[0].shape.points[0].x, stopsEntities[0].shape.points[0].y);
        }

        upStopId = 0;
        downStopId = 0;
        upDistance = Math.sqrt((busLineEntity[0].x - upStopCoord.x) * (busLineEntity[0].x - upStopCoord.x) + (busLineEntity[0].y - upStopCoord.y)
                * (busLineEntity[0].y - upStopCoord.y));
        downDistance = Math.sqrt((busLineEntity[0].x - downStopCoord.x) * (busLineEntity[0].x - downStopCoord.x)
                + (busLineEntity[0].y - downStopCoord.y) * (busLineEntity[0].y - downStopCoord.y));
        for (var i = 1; i < busLineEntity.length; i++) {
            tempDistance = Math.sqrt((busLineEntity[i].x - upStopCoord.x) * (busLineEntity[i].x - upStopCoord.x)
                    + (busLineEntity[i].y - upStopCoord.y) * (busLineEntity[i].y - upStopCoord.y));
            if (tempDistance < upDistance) {
                upStopId = i;
                upDistance = tempDistance;
            }
            tempDistance = Math.sqrt((busLineEntity[i].x - downStopCoord.x) * (busLineEntity[i].x - downStopCoord.x)
                    + (busLineEntity[i].y - downStopCoord.y) * (busLineEntity[i].y - downStopCoord.y));
            if (tempDistance < downDistance) {
                downStopId = i;
                downDistance = tempDistance;
                continue;
            }
        }
        if (upStopId < downStopId) {
            for (var i = 0; i <= downStopId - upStopId; i++) {
                points[i + maxPointNum] = new SuperMap.IS.MapCoord(busLineEntity[i + upStopId].x, busLineEntity[i + upStopId].y);
            }
        } else {
            for (var i = 0; i <= upStopId - downStopId; i++) {
                points[upStopId - downStopId - i + maxPointNum] = new SuperMap.IS.MapCoord(busLineEntity[i + downStopId].x, busLineEntity[i
                        + downStopId].y);
            }
        }
        maxPointNum += (Math.abs(downStopId - upStopId) + 1);
        busLineNum++;
        if (busLineNum < currentRouting.busLines.length) {
            var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
            MapControl1.GetEntity(MapControl1.mapName, "BusLine@changchun", currentRouting.busLines[busLineNum].smId, OnGetComplete, OnError);
        } else {
            var areas = new Array();
            for (var i = 0; i < points.length; i++) {
                areas[i] = new SuperMap.IS.MapRect(points[i].x - 10, points[i].y - 10, points[i].x + 10, points[i].y + 10);
            }
            bPasueDynamicNavigate = false;
            var step = width < height ? width / 15 : height / 15;
            MapControl1.StartDynamicNavigate(points, areas, "images/walk8.gif", "images/walk2.gif", null, null, true, step, 100, null, "");
        }
    }

    function OnError(e) { }

    function OnInArea(e, r) {
        for (var i = 0; i < pointsName.length; i++) {
            if (r.Contains(points[i])) {
                MapControl1.CustomLayer.CloseInfoWindow("stopName");
                MapControl1.CustomLayer.OpenInfoWindow("stopName", e.x, e.y, 100, 20, resource_busStopName, pointsName[i], 10);
                break;
            }
        }
    }
}

function PauseDynamicNavigate() {
    if (bPasueDynamicNavigate) {
        MapControl1.ContinueDynamicNavigate();
        bPasueDynamicNavigate = false;
    } else {
        MapControl1.PauseDynamicNavigate();
        bPasueDynamicNavigate = true;
    }
}

function StopDynamicNavigate() {
    bPasueDynamicNavigate = false;
    MapControl1.StopDynamicNavigate();
}

function SwitchMap() {
    var doc = document;
    var sel = doc.getElementById("selMapNames");
    var btn1 = doc.getElementById('Button1');
    var btn2 = doc.getElementById('GetBusSolution1');
    var mapName = sel.options[sel.selectedIndex].value;
    if (mapName != 'changchun') {
        if (btn1 != null) {
            btn1.disabled = true;
        }
        if (btn2 != null) {
            btn2.disabled = true;
        }
    }
    else {
        if (btn1 != null) {
            btn1.disabled = false;
        }
        if (btn2 != null) {
            btn2.disabled = false;
        }
    }
    MapControl1.mapName = mapName;
    MapControl1.Update();
    if (m_layers) {
        while (m_layers.length > 0) {
            var layer = m_layers.pop();
            layer.Destroy();
            layer = null;
        }
    }
    currentRouting = null;
    MapControl1.StopDynamicNavigate();
    if (MapControl1.mapName != "changchun") {
        tolerance = 5;
    } else {
        tolerance = 200;
    }
}

function AddEntityAction() {
    var infos = document.getElementById("EditLayers").value.split(',');
    var addEntityAction = new SuperMap.IS.AddEntityAction(infos[0], eval(infos[1]), onAddEntityComplete, null, null, lockID);
    MapControl1.SetAction(addEntityAction);
}

function onAddEntityComplete(editResult) {
    if (!editResult.succeed) {
        OnActionError(editResult.message, "AddEntity");
        return;
    }
    RefreshOverview;
}

//刷新鹰眼
function RefreshOverview() {
    if (OverviewControl1) {
        OverviewControl1.Update();
    }
}

var updateEntityAction;
var _propertyNames = null;
var _propertyValues = null;
function UpdateEntityAction() {

    var infos = document.getElementById("EditLayers").value.split(',');
    updateEntityAction = new SuperMap.IS.UpdateEntityAction(infos[0], eval(infos[1]), null, null, null, lockID);
    MapControl1.SetAction(updateEntityAction);

    var _modifyWindow = null;
    var _selected;
    var actionStarted = false;
    var xs = new Array();
    var ys = new Array();
    var keyPoints = new Array();
    var firstMapCoord = null;
    layerName = infos[0];
    var layerType = eval(infos[1]);
    var _type = layerType;
    var _layerName = layerName;
    var _queryParam = new SuperMap.IS.QueryParam();
    var myMapControl = updateEntityAction.mapControl;
    _queryParam.queryLayers = new Array();
    var ql = new SuperMap.IS.QueryLayer();
    ql.layerName = layerName;
    _queryParam.queryLayers.push(ql);
    _queryParam.expectCount = 1;
    _queryParam.highlight = new SuperMap.IS.Highlight();
    _queryParam.highlight.highlightQueryArea = false;
    _queryParam.highlight.highlightResult = false;

    function OnQueryComplete(resultSet) {

        if (resultSet != null && resultSet.currentCount == 1) {
            //高亮出来
            if (_type == SuperMap.IS.LayerType.point) {
                var x = resultSet.recordsets[0].records[0].center.x;
                var y = resultSet.recordsets[0].records[0].center.y;
                var innerHtml = "<div style='font-size:16px; color:blue; font-weight:bold'><img src='images/marker.gif' style='cursor:hand' /></div>";
                updateEntityAction.mapControl.CustomLayer.InsertMark("PointUpdating", x, y, 10, 10, innerHtml);
                _id = resultSet.recordsets[0].records[0].fieldValues[0];
                _selected = true;
            }
            if (_type == SuperMap.IS.LayerType.line) {
                //没有点串信息,只好再GetEntity
                updateEntityAction.mapControl.GetEntity(updateEntityAction.mapControl.mapName, layerName,
                        eval(resultSet.recordsets[0].records[0].fieldValues[0]), OnGetEntityComplete);
            }
            if (_type == SuperMap.IS.LayerType.polygon) {
                //没有点串信息,只好再GetEntity
                updateEntityAction.mapControl.GetEntity(updateEntityAction.mapControl.mapName, layerName,
                        eval(resultSet.recordsets[0].records[0].fieldValues[0]), OnGetEntityComplete);
            }
            if (resultSet.recordsets[0].returnFields) {
                if (_propertyNames == null) {
                    _propertyNames = new Array();
                }
                for (var i = 0; i < resultSet.recordsets[0].returnFields.length; i++) {
                    _propertyNames[i] = resultSet.recordsets[0].returnFields[i];
                }
            }
            if (resultSet.recordsets[0].records[0].fieldValues) {
                if (_propertyValues == null) {
                    _propertyValues = new Array();
                }
                for (var i = 0; i < resultSet.recordsets[0].records[0].fieldValues.length; i++) {
                    _propertyValues[i] = resultSet.recordsets[0].records[0].fieldValues[i];
                }
            }
            _ModifyProperty();
        }

    }

    function OnGetEntityComplete(entity) {
        if (entity != null && entity.shape != null) {
            _id = entity.id;
            var pointsX = new Array();
            var pointsY = new Array();
            for (var i = 0; i < entity.shape.points.length; i++) {
                pointsX.push(entity.shape.points[i].x);
                pointsY.push(entity.shape.points[i].y);
            }
            if (_type == SuperMap.IS.LayerType.line) {
                updateEntityAction.mapControl.CustomLayer.InsertLine("LineUpdating", pointsX, pointsY, 2, "blue", null, null, null, entity.shape.parts);
            }
            if (_type == SuperMap.IS.LayerType.polygon) {
                updateEntityAction.mapControl.CustomLayer.InsertPolygon("PolygonUpdating", pointsX, pointsY, 2, "blue", "white", 0.6, 1, null, entity.shape.parts);
            }
            //清空一下
            while (pointsX.length > 0) {
                pointsX.pop();
                pointsY.pop();
            }
            pointsX = null;
            pointsY = null;
            _selected = true;

        }
    }
    updateEntityAction.Destroy = function() {
        myMapControl.CustomLayer.RemoveMark("PointUpdating");
        myMapControl.CustomLayer.RemoveLine("LineUpdating");
        myMapControl.CustomLayer.RemoveLine("LineDrawing");
        myMapControl.CustomLayer.RemovePolygon("PolygonUpdating");
        myMapControl.CustomLayer.RemovePolygon("PolygonDrawing");
        myMapControl = null;
        OpenMenuBody(1, 12);
        //        container.innerHTML = resource_selectEntity;

    }

    updateEntityAction.SetEditLayer = function(editLayerName, editLayerType) {
        _type = editLayerType;
        _layerName = editLayerName;
        _queryParam.queryLayers.pop();
        var ql = new SuperMap.IS.QueryLayer();
        ql.layerName = editLayerName;
        _queryParam.queryLayers.push(ql);
    }

    updateEntityAction.OnClick = function(e) {
        if (layerName != _layerName) {
            _selected = false;
            actionStarted = false;
            while (keyPoints.length > 0) {
                keyPoints.pop();
            }
            while (xs.length > 0) {
                xs.pop(); ys.pop();
            }
            firstMapCoord = null;
            updateEntityAction.mapControl.CustomLayer.RemoveMark("PointUpdating");
            updateEntityAction.mapControl.CustomLayer.RemoveLine("LineUpdating");
            updateEntityAction.mapControl.CustomLayer.RemoveLine("LineDrawing");
            updateEntityAction.mapControl.CustomLayer.RemovePolygon("PolygonUpdating");
            updateEntityAction.mapControl.CustomLayer.RemovePolygon("PolygonDrawing");
        }
        layerName = _layerName;
        layerType = _type;
        if (layerType == SuperMap.IS.LayerType.point) {
            if (!_selected) {
                //还没有选中点对象先进行一次查询
                updateEntityAction.mapControl.GetQueryManager().FindNearest(e.mapCoord, 100, _queryParam, OnQueryComplete);
            } else {
                var entity = new SuperMap.IS.Entity();
                entity.shape = new SuperMap.IS.Geometry();
                entity.id = _id;
                entity.shape.parts = new Array();
                entity.shape.feature = layerType;
                var mapCoord = e.mapCoord;
                entity.shape.points = new Array(e.mapCoord);
                var entities = new Array(entity);
                if (lockID) {
                    updateEntityAction.mapControl.GetEditManager().UpdateEntityByUserID(updateEntityAction.mapControl.mapName, layerName, entities, lockID,
                        OnUpdateEntityComplete, OnActionError);
                } else {
                    updateEntityAction.mapControl.GetEditManager().UpdateEntity(updateEntityAction.mapControl.mapName, layerName, entities,
                        OnUpdateEntityComplete, OnActionError);
                }
            }
        }
        if (layerType == SuperMap.IS.LayerType.line) {
            if (!_selected) {
                // 还没有选中点对象先进行一次查询
                updateEntityAction.mapControl.GetQueryManager().FindNearest(e.mapCoord, 100, _queryParam, OnQueryComplete, OnActionError);
            } else {
                // 已选中对象,可以开始更新
                if (!actionStarted) {
                    keyPoints.push(e.mapCoord);
                    xs.push(e.mapCoord.x);
                    ys.push(e.mapCoord.y);
                }
                actionStarted = true;
                keyPoints.push(e.mapCoord);
                xs.push(e.mapCoord.x);
                ys.push(e.mapCoord.y);
            }
        }
        if (layerType == SuperMap.IS.LayerType.polygon) {
            if (!_selected) {
                // 还没有选中点对象先进行一次查询
                updateEntityAction.mapControl.GetQueryManager().FindNearest(e.mapCoord, 100, _queryParam, OnQueryComplete, OnActionError);
            } else {
                if (!actionStarted) {
                    firstMapCoord = e.mapCoord;
                    xs.push(e.mapCoord.x);
                    ys.push(e.mapCoord.y);

                } else {
                    xs.pop();
                    ys.pop();
                    xs.push(e.mapCoord.x);
                    ys.push(e.mapCoord.y);
                }
                actionStarted = true;
                keyPoints.push(e.mapCoord);
                xs.push(firstMapCoord.x);
                ys.push(firstMapCoord.y);

            }
        }

    };

    updateEntityAction.OnDblClick = function(e) {
        if (!actionStarted) { return false; }
        if (_selected) {
            if (layerType == SuperMap.IS.LayerType.line) {
                keyPoints.push(e.mapCoord);
                xs.push(e.mapCoord.x);
                ys.push(e.mapCoord.y);
                updateEntityAction.mapControl.CustomLayer.RemoveLine("LineDrawing");
                var entity = new SuperMap.IS.Entity();
                entity.shape = new SuperMap.IS.Geometry();
                entity.id = _id;
                entity.shape.parts = new Array();
                entity.shape.feature = layerType;
                entity.shape.points = keyPoints;
                var entities = new Array(entity);
                if (lockID) {
                    updateEntityAction.mapControl.GetEditManager().UpdateEntityByUserID(updateEntityAction.mapControl.mapName, layerName, entities, lockID,
                        OnUpdateEntityComplete, OnActionError);
                } else {
                    updateEntityAction.mapControl.GetEditManager().UpdateEntity(updateEntityAction.mapControl.mapName, layerName, entities,
                        OnUpdateEntityComplete, OnActionError);
                }
                while (keyPoints.length > 0) {
                    keyPoints.pop();
                }
                while (xs.length > 0) {
                    xs.pop();
                    ys.pop();
                }
                firstMapCoord = null;
                actionStarted = false;

            }
            if (layerType == SuperMap.IS.LayerType.polygon) {
                keyPoints.push(e.mapCoord);
                keyPoints.push(firstMapCoord);
                xs.pop();
                ys.pop();
                xs.push(e.mapCoord.x);
                ys.push(e.mapCoord.y);
                xs.push(firstMapCoord.x);
                ys.push(firstMapCoord.y);
                updateEntityAction.mapControl.CustomLayer.RemoveLine("PolygonDrawing");
                var entity = new SuperMap.IS.Entity();
                entity.shape = new SuperMap.IS.Geometry();
                entity.id = _id;
                entity.shape.parts = new Array();
                entity.shape.feature = layerType;
                entity.shape.points = keyPoints;
                var entities = new Array(entity);
                if (lockID) {
                    updateEntityAction.mapControl.GetEditManager().UpdateEntityByUserID(updateEntityAction.mapControl.mapName, layerName, entities, lockID,
                        OnUpdateEntityComplete, OnActionError);
                } else {
                    updateEntityAction.mapControl.GetEditManager().UpdateEntity(updateEntityAction.mapControl.mapName, layerName, entities,
                        OnUpdateEntityComplete, OnActionError);
                }
                while (keyPoints.length > 0) {
                    keyPoints.pop();
                }
                while (xs.length > 0) {
                    xs.pop();
                    ys.pop();
                }
                firstMapCoord = null;
                actionStarted = false;
            }
        }
    };

    updateEntityAction.OnMouseMove = function(e) {
        if (!actionStarted) { return false; }
        if (layerType == SuperMap.IS.LayerType.line) {
            keyPoints.pop();
            xs.pop();
            ys.pop();
            keyPoints.push(e.mapCoord);
            xs.push(e.mapCoord.x);
            ys.push(e.mapCoord.y);
            updateEntityAction.mapControl.CustomLayer.InsertLine("LineDrawing", xs, ys, 2, "blue");
        }
        if (layerType == SuperMap.IS.LayerType.polygon) {
            keyPoints.pop();
            xs.pop();
            ys.pop();
            keyPoints.push(e.mapCoord);
            xs.push(e.mapCoord.x);
            ys.push(e.mapCoord.y);
            updateEntityAction.mapControl.CustomLayer.InsertPolygon("PolygonDrawing", xs, ys, 2, "blue", "white", 0.6, 1);
        }
        e.cancelTriggerGeometryEvent = true;
    };
    updateEntityAction.OnContextMenu = function(e) {
        _selected = false;
        actionStarted = false;
        while (keyPoints.length > 0) {
            keyPoints.pop();
        }
        while (xs.length > 0) {
            xs.pop(); ys.pop();
        }
        firstMapCoord = null;
        updateEntityAction.mapControl.CustomLayer.RemoveMark("PointUpdating");
        updateEntityAction.mapControl.CustomLayer.RemoveLine("LineUpdating");
        updateEntityAction.mapControl.CustomLayer.RemoveLine("LineDrawing");
        updateEntityAction.mapControl.CustomLayer.RemovePolygon("PolygonUpdating");
        updateEntityAction.mapControl.CustomLayer.RemovePolygon("PolygonDrawing");
    };
    function _ModifyProperty() {
        _modifyWindow = document.getElementById("ModifyDiv");
        if (!_modifyWindow) {
            _modifyWindow = document.createElement("Div");
            _modifyWindow.id = "ModifyDiv";
            //            _modifyWindow.style.width = "200px";
            _modifyWindow.style.height = "180px";
            //            _modifyWindow.style.border = "solid 1px black";
            _modifyWindow.style.backgroundColor = "white";
            _modifyWindow.style.overflow = "auto";
            _modifyWindow.style.zIndex = 10;

            var container = document.getElementById("PropertyForm");
            container.innerHTML = "";
            container.appendChild(_modifyWindow);
            if (container.style.display = "none") {
                OpenMenuBody(9, 12, true);
                container.style.display = "block";
            }
        } else {
            var container = document.getElementById("PropertyForm");
            if (container.style.display = "none") {
                OpenMenuBody(9, 12, true);
                container.style.display = "block";
            }
        }
        var strTable = "<table>";
        strTable += "<tr><td>" + resource_updateCoord + "</td></tr>";
        for (var i = 0; i < _propertyNames.length; i++) {
            var propertyName = _propertyNames[i].toLowerCase();
            if (propertyName.substring(0, 2) != "sm") {
                strTable += "<tr>";
                strTable += "<td width='50%'>" + _propertyNames[i] + "</td>";
                strTable += "<td width='50%'><input style='width:50px; ' id='" + _propertyNames[i] + "'";
                if (_propertyValues[i]) {
                    strTable += "value='" + _propertyValues[i] + "'";
                }
                strTable += "></td>";
                strTable += "</tr>";
            }

        }
        strTable += "<tr>";
        strTable += "<td><input id='SubmitUpdate' type='button' onclick='_SubmitUpdate();' value='submit'></td>";
        strTable += "<td><input id='CancelUpdate' type='button' onclick='_Cancel();' value='cancel'></td>";
        strTable += "</tr></table>";
        _modifyWindow.innerHTML = strTable;
    }
}

function _SubmitUpdate(e) {
    var infos = document.getElementById("EditLayers").value.split(',');
    var entity = new SuperMap.IS.Entity();
    entity.shape = new SuperMap.IS.Geometry();
    entity.id = _id;
    entity.shape.parts = new Array();
    entity.shape.feature = eval(infos[1]);
    entity.shape.id = _id;
    entity.fieldValues = new Array();
    entity.fieldNames = new Array();
    var mapCoord = new SuperMap.IS.MapCoord();
    for (var i = 0; i < _propertyNames.length; i++) {

        if (_propertyNames[i].substring(0, 2).toLowerCase() != "sm") {
            var textbox = document.getElementById(_propertyNames[i]);
            entity.fieldNames[i] = _propertyNames[i];
            if (textbox.value) {
                //先编码处理特殊字符
                entity.fieldValues[i] = escape(textbox.value);
            } else {
                entity.fieldValues[i] = null;
            }
        }
    }
    entity.shape.points = null;

    var entities = new Array(entity);
    if (lockID) {
        updateEntityAction.mapControl.GetEditManager().UpdateEntityByUserID(updateEntityAction.mapControl.mapName, infos[0], entities, lockID, OnUpdateEntityComplete,
            OnActionError);
    } else {
        updateEntityAction.mapControl.GetEditManager().UpdateEntity(updateEntityAction.mapControl.mapName, infos[0], entities, OnUpdateEntityComplete,
            OnActionError);
    }
}
function _Cancel() {
    _selected = false;
    updateEntityAction.mapControl.CustomLayer.RemoveMark("PointUpdating");
    updateEntityAction.mapControl.CustomLayer.RemoveLine("LineUpdating");
    updateEntityAction.mapControl.CustomLayer.RemovePolygon("PolygonUpdating");
    updateEntityAction.mapControl.CustomLayer.RemovePolygon("PolygonDrawing");
    updateEntityAction.mapControl = null;
    var container = document.getElementById("PropertyForm");
    container.innerHTML = resource_selectEntity;
    container.style.display = "none";
    UpdateEntityAction();
}

function OnUpdateEntityComplete(editResult) {
    if (!editResult.succeed) {
        OnActionError(editResult.message, "UpdateEntity");
        return;
    }
    updateEntityAction.mapControl.Update();
    RefreshOverview();
    _selected = false;
    updateEntityAction.mapControl.CustomLayer.RemoveMark("PointUpdating");
    updateEntityAction.mapControl.CustomLayer.RemoveLine("LineUpdating");
    updateEntityAction.mapControl.CustomLayer.RemovePolygon("PolygonUpdating");
    updateEntityAction.mapControl.CustomLayer.RemovePolygon("PolygonDrawing");
    var container = document.getElementById("PropertyForm");
    container.innerHTML = resource_selectEntity;
    //    container.style.display = "none";
    UpdateEntityAction();
}

function DeleteEntityAction() {
    var doc = document;
    var infos = doc.getElementById("EditLayers").value.split(',');
    var deleteEntityAction = new SuperMap.IS.DeleteEntityAction(infos[0], eval(infos[1]), null, null, null, lockID);
    MapControl1.SetAction(deleteEntityAction);
    infos = doc.getElementById("EditLayers").value.split(',');
    var layerName = infos[0];
    var layerType = eval(infos[1]);
    var _layerName = layerName;
    var _type = layerType;
    _queryParam = new SuperMap.IS.QueryParam();
    _queryParam.queryLayers = new Array();
    var ql = new SuperMap.IS.QueryLayer();
    ql.layerName = layerName;
    _queryParam.queryLayers.push(ql);
    _queryParam.expectCount = 1;
    _queryParam.highlight = new SuperMap.IS.Highlight();
    _queryParam.highlight.highlightQueryArea = false;
    _queryParam.highlight.highlightResult = false;
    var myMapControl = deleteEntityAction.mapControl;

    deleteEntityAction.SetEditLayer = function(editLayerName, editLayerType) {
        _type = editLayerType;
        _layerName = editLayerName;
        _queryParam.queryLayers.pop();
        var ql = new SuperMap.IS.QueryLayer();
        ql.layerName = editLayerName;
        _queryParam.queryLayers.push(ql);
    }

    deleteEntityAction.OnClick = function(e) {
        if (layerName != _layerName) {
            myMapControl.CustomLayer.RemoveMark("PointDeleting");
            myMapControl.CustomLayer.RemoveLine("LineDeleting");
            myMapControl.CustomLayer.RemovePolygon("PolygonDeleting");
        }
        layerName = _layerName;
        layerType = _type;

        deleteEntityAction.mapControl.GetQueryManager().FindNearest(e.mapCoord, 100, _queryParam, OnQueryComplete);
    };

    function _Delete() {
        if (_selected) {
            var entity = new SuperMap.IS.Entity();
            var ids = new Array();
            ids.push(_id);
            if (confirm(resource_deleteComfirm)) {
                if (lockID) {
                    deleteEntityAction.mapControl.GetEditManager().DeleteEntityByUserID(deleteEntityAction.mapControl.mapName, layerName, ids, lockID,
                        OnDeleteEntityComplete);
                } else {
                    deleteEntityAction.mapControl.GetEditManager().DeleteEntity(deleteEntityAction.mapControl.mapName, layerName, ids,
                        OnDeleteEntityComplete);
                }
            }
        }
    }
    function OnDeleteEntityComplete(editResult) {
        if (!editResult.succeed) {
            OnActionError(editResult.message, "DeleteEntity");
            return;
        }
        deleteEntityAction.mapControl.Update();
        RefreshOverview();
        _selected = false;
        deleteEntityAction.mapControl.CustomLayer.RemoveMark("PointDeleting");
        deleteEntityAction.mapControl.CustomLayer.RemoveLine("LineDeleting");
        deleteEntityAction.mapControl.CustomLayer.RemovePolygon("PolygonDeleting");

    }

    function OnGetEntityComplete(entity) {
        if (entity != null && entity.shape != null) {
            _id = entity.id;
            var pointsX = new Array();
            var pointsY = new Array();
            for (var i = 0; i < entity.shape.points.length; i++) {
                pointsX.push(entity.shape.points[i].x);
                pointsY.push(entity.shape.points[i].y);
            }
            if (_type == SuperMap.IS.LayerType.line) {
                deleteEntityAction.mapControl.CustomLayer.InsertLine("LineDeleting", pointsX, pointsY, 2, "blue", null, null, null, entity.shape.parts);
            }
            if (_type == SuperMap.IS.LayerType.polygon) {
                deleteEntityAction.mapControl.CustomLayer.InsertPolygon("PolygonDeleting", pointsX, pointsY, 2, "blue", "white", 0.6, 1, null, entity.shape.parts);
            }
            //清空一下
            while (pointsX.length > 0) {
                pointsX.pop();
                pointsY.pop();
            }
            pointsX = null;
            pointsY = null;
            _selected = true;
            _Delete();
        }
    }

    function OnQueryComplete(resultSet) {

        if (resultSet != null && resultSet.currentCount == 1) {
            //高亮出来
            if (_type == SuperMap.IS.LayerType.point) {
                var x = resultSet.recordsets[0].records[0].center.x;
                var y = resultSet.recordsets[0].records[0].center.y;
                var innerHtml = "<div style='font-size:16px; color:blue; font-weight:bold;overflow:hidden;height:180px;width:200px;'><img src='images/marker.gif' style='cursor:hand' /></div>";
                deleteEntityAction.mapControl.CustomLayer.InsertMark("PointDeleting", x, y, 20, 20, innerHtml);
                _id = resultSet.recordsets[0].records[0].fieldValues[0];
                _selected = true;
                _Delete();
            }
            if (_type == SuperMap.IS.LayerType.line) {
                //没有点串信息,只好再GetEntity
                deleteEntityAction.mapControl.GetEntity(deleteEntityAction.mapControl.mapName, layerName,
                        eval(resultSet.recordsets[0].records[0].fieldValues[0]), OnGetEntityComplete);
            }
            if (_type == SuperMap.IS.LayerType.polygon) {
                //没有点串信息,只好再GetEntity
                deleteEntityAction.mapControl.GetEntity(deleteEntityAction.mapControl.mapName, layerName,
                        eval(resultSet.recordsets[0].records[0].fieldValues[0]), OnGetEntityComplete);
            }
        } else {
            deleteEntityAction.mapControl.CustomLayer.RemoveMark("PointDeleting");
            deleteEntityAction.mapControl.CustomLayer.RemoveLine("LineDeleting");
            deleteEntityAction.mapControl.CustomLayer.RemovePolygon("PolygonDeleting");
            _id = -1;
            _selected = false;
        }
    }
}

function RenderLayerToSelect(id) {
    var select = document.getElementById(id);
    if (!select) { return; }
    while (select.options.length > 0) {
        select.options[0] = null;
        //netscape下不支持这么,so...
        //select.options.remove(0);
    }
    if (!MapControl1.layers || !MapControl1.layers.length) { return; }
    for (var i = 0; i < MapControl1.layers.length; i++) {
        //过滤一下,只有点线面
        var layerType = MapControl1.layers[i].type;
        if (layerType != SuperMap.IS.LayerType.point && layerType != SuperMap.IS.LayerType.line && layerType != SuperMap.IS.LayerType.polygon && layerType != SuperMap.IS.LayerType.cad) {
            continue;
        }
        var oOption = document.createElement("OPTION");
        select.options.add(oOption);
        oOption.innerText = MapControl1.layers[i].name.split("@")[0];
        switch (id) {
            case "EditLayers":
                oOption.value = MapControl1.layers[i].name + "," + layerType;
                break;
            case "LayerInfo":
            case "SqlQueryLayer":
                oOption.value = i;
                break;

            case "selBufferLayers":
            case "selQueryLayer":
                oOption.value = MapControl1.layers[i].name;
                break;
        }
    }
    select = null;
}

function RenderMapNames() {
    var selMapNames = document.getElementById("selMapNames");

    while (selMapNames.options.length > 0) {
        selMapNames.remove(0);
    }
    for (var i = 0; i < MapControl1.mapNames.length; i++) {
        var mnOption = document.createElement("OPTION");
        selMapNames.options.add(mnOption);
        mnOption.innerText = MapControl1.mapNames[i];
        mnOption.value = MapControl1.mapNames[i];
        mnOption.selected = false;
    }
    for (var i = 0; i < selMapNames.options.length; i++) {
        if (MapControl1.mapName == selMapNames.options[i].value) {
            selMapNames.options[i].selected = true;
        }
    }
}

function RenderEditLayers() {
    RenderLayerToSelect("EditLayers");
    RenderLayerToSelect("LayerInfo");
    RenderLayerToSelect("SqlQueryLayer");
    RenderLayerToSelect("selBufferLayers");
    RenderLayerToSelect("selQueryLayer");
    GetFieldFromLayer("LayerInfo", "Expression");
    GetFieldFromLayer("SqlQueryLayer", "selSqlFields");
}

function RenderPositionInfo() {
    var x = document.getElementById("PositionX");
    var y = document.getElementById("PositionY");
    var scale = document.getElementById("PositionScale");
    x.value = MapControl1.GetMapCenterX();
    y.value = MapControl1.GetMapCenterY();
    var mapParam = MapControl1.GetMapParam();
    if (mapParam.mapScales && mapParam.mapScales.length > 0) {
        scale.value = Math.round(1 / parseFloat(MapControl1.GetMapScale()));
    } else {
        scale.value = 1 / parseFloat(MapControl1.GetMapScale());
    }
    if (MapControl1) {
        MapControl1.AttachEvent("onchangeview", RenderPositionInfo);
    }
}

function MapPosition() {
    var x = document.getElementById("PositionX").value;
    x = parseFloat(x);
    if (x != 0 && !x) { return; }
    var y = document.getElementById("PositionY").value;
    y = parseFloat(y);
    if (y != 0 && !y) { return; }
    var scale = document.getElementById("PositionScale").value;
    scale = parseFloat(scale);
    if (!scale) { return; }

    var center = new SuperMap.IS.MapCoord(x, y);
    var mp = MapControl1.GetMapParam();
    mp.SetMapScale(1 / scale);
    mp.SetMapCenter(center);
    MapControl1.SetMapParam(mp);
}

//一般查询
function SqlQuery(tname) {

    var select = document.getElementById(tname).value;
    if(select ==null || select =="")
    {
        alert("没有输入查询名称，请输入要查询的地方名称或名称关键字！");
        //closeMyPlace('menu_2_content');
        return;
    }
    var queryParam = new SuperMap.IS.QueryParam();
//	var hl = new SuperMap.IS.Highlight();
//	var stly = new SuperMap.IS.Style();
//	//hl.highlightQueryArea=true;
//	//hl.highlightResult = false;
//	hl.pointStyle = stly.symbolStyle(3);
//	queryParam.highlight = hl;
 queryParam.highlight = new SuperMap.IS.Highlight();
    
    queryParam.highlight.highlightQueryArea = true;
    queryParam.highlight.pointStyle = new SuperMap.IS.Style();
    //queryParam.highlight.pointStyle.brushColor = 0X00FF00;  //设置填充的颜色为蓝色 
    //queryParam.highlight.pointStyle.brushBackColor = 0X00FF00;  //设置填充的颜色为蓝色 
    queryParam.highlight.pointStyle.brushOpaqueRate = 0;
//    queryParam.highlight.pointStyle.symbolSize = 5;
    queryParam.highlight.pointStyle.penColor = 2;
    queryParam.highlight.pointStyle.penStyle = 4;
    queryParam.highlight.pointStyle.symbolStyle = 120; //工作空间的图片索引
    
    queryParam.IsAllLayer = false; // 设置查询模式为不查询所有图层

    queryParam.queryLayers = new Array(1);
    //
    //var tables = "P_Jiaotongfuwu@SXWebMeta,P_XueXiao@SXWebMeta,P_Yiliaoweisheng@SXWebMeta,P_Jiayouzhan@SXWebMeta,P_Lvyoujingdian@SXWebMeta,P_Xiezilou@SXWebMeta,P_Yinhang@SXWebMeta,P_Binguanjiudian@SXWebMeta,P_Gongchang@SXWebMeta,P_Youzheng@SXWebMeta,P_Yulechangsuo@SXWebMeta,P_Gongjianfa@SXWebMeta,P_Nonglinmuyu@SXWebMeta,P_Shichang@SXWebMeta,P_Dangzhengjiguan@SXWebMeta,P_Xian,P_Xiang@SXWebMeta,P_Zhengfuqitaju@SXWebMeta,P_Cun@SXWebMeta,P_Jituangongsi@SXWebMeta,P_Tongxun@SXWebMeta,P_GongCe@SXWebMeta,P_Canyin@SXWebMeta,P_QiChefuwu@SXWebMeta,P_Tingchechang@SXWebMeta,P_Falvzixun@SXWebMeta,P_Richangfuwu@SXWebMeta";
    //var tName = tables.split(',');
 
        var queryLayer2 = new SuperMap.IS.QueryLayer();
        queryLayer2.whereClause = " NAME like '%"+select+"%' ";
        queryLayer2.layerName = tables;
        queryParam.queryLayers[0] = queryLayer2;

    queryParam.expectCount = parseInt("10000");
    var queryManager = MapControl1.GetQueryManager();
    var resultSet = queryManager.QueryBySql(queryParam, OnQuerySuceess, OnActionError,tname);
    select = null;
    waiting();
}

//一般查询
function SqlQuery1(tname) {
    var select = document.getElementById(tname).value;
    if(select ==null || select =="")
    {
        alert("没有输入查询名称，请输入要查询的地方名称或名称关键字！");;
        return;
    }
    var queryParam = new SuperMap.IS.QueryParam();


    queryParam.queryLayers = new Array(26);
    var tName = tables.split(',');
    for(var i=0;i<tName.length;i++)
    {
        var queryLayer2 = new SuperMap.IS.QueryLayer();
        queryLayer2.whereClause = " NAME like '%"+select+"%' ";
        queryLayer2.layerName = tName[i];
        queryParam.queryLayers[i] = queryLayer2;
    }
    queryParam.expectCount = parseInt("10000");
    var queryManager = MapControl1.GetQueryManager();
    var resultSet = queryManager.QueryBySql(queryParam, OnQuerySuceess1, OnActionError,tname);
    select = null;
}
function SqlQueryTC(divids,TCname) {
    var doc = document;
    
    var queryParam = new SuperMap.IS.QueryParam();
    queryParam.IsAllLayer = false; // 设置查询模式为不查询所有图层
    queryParam.queryLayers = new Array();
    var queryLayer2 = new SuperMap.IS.QueryLayer();
    queryLayer2.whereClause = " NAME like '%%' ";
    queryLayer2.layerName = TCname;
    queryParam.queryLayers[0] = queryLayer2;
    queryParam.expectCount = parseInt("10000");
    var queryManager = MapControl1.GetQueryManager();
    var resultSet = queryManager.QueryBySql(queryParam, OnQuerySuceess, OnActionError,divids);
    select = null;
}


function MoveEntityAction() {
    var infos = document.getElementById("EditLayers").value.split(',');
    var moveEntityAction = new SuperMap.IS.MoveEntityAction(infos[0], eval(infos[1]), onAddEntityComplete, null, null, lockID);
    MapControl1.SetAction(moveEntityAction);
}

// 执行缓冲查询
function bufferQuery() {
    // 设置缓冲参数
    var bufferParam = new SuperMap.IS.BufferParam();
    bufferParam.fromCustomGeo = false;  // 设置对已有图层的几何对象进行缓冲
    bufferParam.fromLayer = new SuperMap.IS.QueryLayer();
//    var select_bufferlayer = document.getElementById("bufferlayer");

//    var index = select_bufferlayer.options[select_bufferlayer.options.selectedIndex].value;
    bufferParam.fromLayer.layerName = "P_Jiaotongfuwu@SXWebMeta";//map.layers[index].name; // 设置缓冲图层名
    bufferParam.fromLayer.whereClause = " NAME like '%车%' ";//document.getElementById("bufferFilter").value;
    bufferParam.distance = parseFloat(5.0);  // 设置缓冲半径
    bufferParam.queryMode = SuperMap.IS.SpatialQueryMode.areaIntersect;
    bufferParam.smoothness = 12;

    // 设置查询参数
//    var select_SqlQueryLayer_Geo = document.getElementById("SqlQueryLayer_Geo");
    var queryParam = new SuperMap.IS.QueryParam();
    queryParam.highlight = new SuperMap.IS.Highlight();
    queryParam.highlight.highlightQueryArea = true;
    queryParam.highlight.queryAreaStyle = new SuperMap.IS.Style();
    queryParam.highlight.queryAreaStyle.brushOpaqueRate = 0;
    queryParam.highlight.queryAreaStyle.penColor = 2;
    queryParam.highlight.queryAreaStyle.penStyle = 2;
    queryParam.IsAllLayer = false; // 设置查询模式为不查询所有图层
    var queryLayer = new SuperMap.IS.QueryLayer();
    var index = 5;// select_SqlQueryLayer_Geo.options[select_SqlQueryLayer_Geo.options.selectedIndex].value;
    queryLayer.layerName = "P_Jiaotongfuwu@SXWebMeta";//map.layers[index].name; // 设置查询图层名
    queryParam.queryLayers = new Array(1);
    queryParam.queryLayers[0] = queryLayer;
    queryParam.expectCount = 1000;

//    var tables = "P_Jiaotongfuwu@SXWebMeta,P_XueXiao@SXWebMeta,P_Yiliaoweisheng@SXWebMeta,P_Jiayouzhan@SXWebMeta,P_Lvyoujingdian@SXWebMeta,P_Xiezilou@SXWebMeta,P_Yinhang@SXWebMeta,P_Binguanjiudian@SXWebMeta,P_Gongchang@SXWebMeta,P_Youzheng@SXWebMeta,P_Yulechangsuo@SXWebMeta,P_Gongjianfa@SXWebMeta,P_Nonglinmuyu@SXWebMeta,P_Shichang@SXWebMeta,P_Dangzhengjiguan@SXWebMeta,P_Xian,P_Xiang@SXWebMeta,P_Zhengfuqitaju@SXWebMeta,P_Cun@SXWebMeta,P_Jituangongsi@SXWebMeta,P_Tongxun@SXWebMeta,P_GongCe@SXWebMeta,P_Canyin@SXWebMeta,P_QiChefuwu@SXWebMeta,P_Tingchechang@SXWebMeta,P_Falvzixun@SXWebMeta,P_Richangfuwu@SXWebMeta";
//    var tName = tables.split(',');
//    for(var i=0;i<tName.length;i++)
//    {
//    var queryLayer2 = new SuperMap.IS.QueryLayer();
//    queryLayer2.whereClause = " NAME like '%车%' ";
//    queryLayer2.layerName = tName[i];
//    queryParam.queryLayers[i] = queryLayer2;
//    }

    // 获取空间分析对象，进行缓冲查询
    var spatialAnalystManager = MapControl1.GetSpatialAnalystManager();
    var resultSet = spatialAnalystManager.BufferQuery(bufferParam, queryParam, OnQueryComplete, OnActionError);
    select_bufferlayer = null;
    select_SqlQueryLayer_Geo = null;
}

function GetFieldFromLayer(selLayersId, selFieldId) {
    var layerInfo = document.getElementById(selLayersId);
    if (!layerInfo || layerInfo.selectedIndex < 0) { return; }
    var selectedOption = layerInfo.options[layerInfo.selectedIndex];
    var layerIndex = parseInt(selectedOption.value);
    var layer = MapControl1.layers[layerIndex];
    var datasource = new SuperMap.IS.Datasource();
    datasource.alias = layer.name.split('@')[1];
    datasource.name = layer.name.split('@')[1];
    var dataset = new SuperMap.IS.Dataset();
    dataset.name = layer.name.split('@')[0];
    var mapName = MapControl1.GetMapParam().mapName;
    MapControl1.GetDatasetInfo(datasource, dataset, OnGetFieldComplete);
    layerInfo = null;
    selectedOption = null;
    function OnGetFieldComplete(result) {
        if (!result || !result.fields) { return; }
        var curMapName = MapControl1.GetMapParam().mapName;
        if (curMapName != mapName) { return; }
        var propertyNames = result.fields;
        var ExpressionSelect = document.getElementById(selFieldId); //"Expression"
        if (!ExpressionSelect) { return; }
        while (ExpressionSelect.options.length > 0) {
            //ExpressionSelect.options[0].parentNode.removeChild(ExpressionSelect.options[0]);
            ExpressionSelect.remove(0);
        }
        for (var i = 0; i < propertyNames.length; i++) {
            var tempOption = document.createElement("OPTION");
            ExpressionSelect.options.add(tempOption);
            tempOption.innerText = propertyNames[i];
            tempOption.value = propertyNames[i];
        }
        UpdateSqlString();
    }
}

function GetQueryableFromLegend() {
    var layersInfo = new Array();
//    for (var i = 0; i < MapControl1.layers.length; i++) {
//        var checkbox = document.getElementById("LayerControl1_" + MapControl1.layers[i].name + ":Q"); //todo: legend控件的Layers居然没有提供，要改。
//        if (checkbox && checkbox.checked) {
//            layersInfo.push(MapControl1.layers[i].name);
//        }
//    }
    layersInfo.push("MapIndexRN1W@SXWebMeta");
    return layersInfo;
}

function AngleToDirection(angle) {
    //0<=angle<360
    while (angle < 0) {
        angle += 360;
    }
    while (angle > 360) {
        angle -= 360;
    }
    if (angle > 337.5 || angle <= 22.5) { return resource_east; }
    if (angle > 22.5 && angle <= 67.5) { return resource_northeast; }
    if (angle > 67.5 && angle <= 112.5) { return resource_north; }
    if (angle > 112.5 && angle <= 157.5) { return resource_northwest; }
    if (angle > 157.5 && angle <= 202.5) { return resource_west; }
    if (angle > 202.5 && angle <= 247.5) { return resource_southwest; }
    if (angle > 247.5 && angle <= 292.5) { return resource_south; }
    if (angle > 292.5 && angle <= 337.5) { return resource_southeast; }
}

// For LayerControl,可扩展
LayerContextMenu = function() {
    var type = "LayerContextMenu";
    var _mainMenu = null;
    var _width = "100px";
    var _height = "100px";
    var _self = this;
    var _index;
    var _layerControl;
    this.json = _ActionToJSON(type, []);
    this.Init = function(mapControl) {
        this.mapControl = mapControl;
    }
    this.OpenContextMenu = function(e, layerControl) {

        //开始扩展，先做一个菜单窗口
        if (_mainMenu != null) {
            document.body.removeChild(_mainMenu);
            _mainMenu = null;
        }
        _CreateMenu(e);
        _index = e.index;
        _layerControl = layerControl
        document.body.appendChild(_mainMenu);
        //创建一个选择项
        var subMenu0 = document.createElement("Div");
        subMenu0.id = "menuForLayer" + e.index + "_0";
        subMenu0.style.index = 5;
        subMenu0.style.width = _width;
        subMenu0.style.paddingLeft = "10px";
        subMenu0.style.paddingTop = "5px";
        subMenu0.onclick = _ChangeVisible;
        subMenu0.onmouseover = _OnMouseOver;
        //        _mainMenu.style.height = "20px";
        if (_self.mapControl.layers[e.index].visible) {
            subMenu0.innerHTML = resource_unvisible;
        } else {
            subMenu0.innerHTML = resource_visible;
        }
        _mainMenu.appendChild(subMenu0);
        var subMenu1 = document.createElement("Div");
        subMenu1.id = "menuForLayer" + e.index + "_1";
        subMenu1.style.index = 5;
        subMenu1.style.width = _width;
        subMenu1.style.paddingLeft = "10px";
        subMenu1.style.paddingTop = "5px";
        subMenu1.style.borderTop = "1px solid gray";
        subMenu1.onclick = _ChangeQueryable;
        subMenu1.onmouseover = _OnMouseOver;
        //        _mainMenu.style.height = "20px";
        if (_self.mapControl.layers[e.index].queryable) {
            subMenu1.innerHTML = resource_unqueryable;
        } else {
            subMenu1.innerHTML = resource_queryable;
        }
        _mainMenu.appendChild(subMenu1);
        var subMenu2 = document.createElement("Div");
        subMenu2.id = "menuForLayer" + e.index + "_1";
        subMenu2.style.index = 5;
        subMenu2.style.width = _width;
        subMenu2.style.paddingLeft = "10px";
        subMenu2.style.paddingTop = "5px";
        subMenu2.style.borderTop = "1px solid gray";
        subMenu2.onmouseover = _OnMouseOver;
        //        _mainMenu.style.height = "20px";
        _mainMenu.appendChild(subMenu2);
        if (_self.mapControl.layers[e.index].themeLabel) {
            subMenu2.innerHTML = resource_deleteLabelTheme;
            subMenu2.onclick = _DelTheme;
        } else {
            subMenu2.innerHTML = resource_createLabelTheme;
            subMenu2.onclick = _MakeDefaultTheme;

        }
    }

    function _OnMouseLeave(e) {
        document.body.removeChild(_mainMenu);
        _mainMenu = null;
    }

    function _OnMouseOver(e) {
        var target = _GetTarget(e);
        target.style.cursor = "pointer";
    }

    //changevisible
    function _ChangeVisible(e) {
        if (_self.mapControl.layers[_index].visible) {
            _self.mapControl.layers[_index].visible = false;
        } else {
            _self.mapControl.layers[_index].visible = true;
        }
        _OnMouseLeave();
        _self.mapControl.Update();
    }

    function _ChangeQueryable(e) {
        if (_self.mapControl.layers[_index].queryable) {
            _self.mapControl.layers[_index].queryable = false;
        } else {
            _self.mapControl.layers[_index].queryable = true;
        }
        _OnMouseLeave();
        _layerControl.Update();
        _self.mapControl.Update();
    }

    function _MakeDefaultTheme(e) {
        if (!_self.mapControl.layers[_index]) { return; }
        var layer = _self.mapControl.layers[_index];
        if (!layer.themeLabel) {
            layer.themeLabel = new SuperMap.IS.LabelTheme();
        }
        layer.themeLabel.caption = layer.name + "Label";
        layer.themeLabel.expression = "smid";
        layer.themeLabel.fixedAngle = true;
        layer.themeLabel.display = new SuperMap.IS.TextStyle();
        layer.themeLabel.display.fixedSize = true;
        layer.themeLabel.display.bgColor = 859845;
        layer.themeLabel.enabled = true;
        _OnMouseLeave();
        _layerControl.Update();
        _self.mapControl.Update();
    }

    function _DelTheme(e) {
        if (!_self.mapControl.layers[_index]) { return; }
        var layer = _self.mapControl.layers[_index];
        layer.themeLabel = null;
        _OnMouseLeave();
        _layerControl.Update();
        _self.mapControl.Update();
    }
    //创建主菜单
    function _CreateMenu(e) {
        _mainMenu = document.createElement("Div");
        _mainMenu.id = "menuForLayer" + e.index;
        _mainMenu.style.index = 5;
        _mainMenu.style.border = "solid 2px gray";
        _mainMenu.style.position = "absolute";
        var scroll = _GetScroll();
        _mainMenu.style.width = _width
        _mainMenu.style.height = _height;
        _mainMenu.style.left = e.clientX + scroll.left;
        _mainMenu.style.top = e.clientY + scroll.top;
        _mainMenu.style.fontSize = "10px";
        _mainMenu.onmouseleave = _OnMouseLeave;
        _mainMenu.style.backgroundImage = "url(images/backgroud.gif)";
    }

};

function GenerateOperator(selectedIndex) {
    var operator = "";
    switch (selectedIndex) {
        case 0:
            return ">"
        case 1:
            return "=";
        case 2:
            return "<";
        case 3:
            return ">=";
        case 4:
            return "<=";
        case 5:
            return "<>";
        case 6:
            return "Like";
        default:
            return "";
    }
}

function UpdateSqlString(objId) {
    var doc = document;
    var oSqlString = doc.getElementById("sqlString");
    var selectField = doc.getElementById("selSqlFields");
    var selectOperator = doc.getElementById("selOperator");
    var txtSqlValue = doc.getElementById("txtSqlvalue");
    var sqlQueryLayer = doc.getElementById("SqlQueryLayer");
    var sqlQueryLayerName = MapControl1.layers[parseInt(sqlQueryLayer.value)].name.split("@")[0];
    var operator = GenerateOperator(selectOperator.selectedIndex);
    oSqlString.value = "select * " + " from " + sqlQueryLayerName + " where " + selectField.value + " " + operator + " "
            + txtSqlValue.value;
}

var busStart = "";
var busEnd = "";
function ChangeBusQueryMode(radioId, divId, MapControlID) {
    var textStart = document.getElementById("startStop");
    if (!textStart) { return; }
    var textEnd = document.getElementById("endStop");
    if (!textEnd) { return; }
    var start = textStart.value.split(',');
    var end = textEnd.value.split(',')
    if (!Number(start[0])) {
        if (textStart.value != "") {
            busStart = textStart.value;
        }
    }
    if (!Number(end[0])) {
        if (textEnd.value != "") {
            busEnd = textEnd.value;
        }
    }

    CancelFindBus(0);

    var radio = document.getElementById(radioId);
    if (!radio) { return; }
    var div = document.getElementById(divId);
    if (!div) { return; }
    var radioBusStop = document.getElementById("BusStopMode");
    if (!radioBusStop) { return; }
    radioBusStop.checked = false;
    var radioMapCoord = document.getElementById("MapCoordMode");
    if (!radioMapCoord) { return; }
    radioMapCoord.checked = false;
    radio.checked = true;
    var divBusStop = document.getElementById("BusStopNameQuery");
    if (!divBusStop) { return; }
    divBusStop.style.display = "none";
    var divMapCoord = document.getElementById("MapCoordQuery");
    if (!divMapCoord) { return; }
    divMapCoord.style.display = "none";
    div.style.display = "block";
    if (radioId != "MapCoordMode") {
        textStart.value = busStart;
        textEnd.value = busEnd;
        SetPanAction();
        return;
    }
    SetGetCoordsAction(2);
}

function CancelFindBus(num) {
    var textStart = document.getElementById("startStop");
    if (!textStart) { return; }
    textStart.value = "";
    var textEnd = document.getElementById("endStop");
    if (!textEnd) { return; }
    textEnd.value = "";
    if (num) {
        busStart = "";
        busEnd = "";
    }
    MapControl1.CustomLayer.ClearMarks();
}

//GetCoordsAction
function GetCoordsAction(num) {
    this.type = "GetCoordsAction";
    var actionStarted;
    var coordscount;
    var Coords = new Array();
    var i;

    this.Init = function(mapControl) {
        this.mapControl = mapControl;
        if (_ygPos.browser == "ie") {
            mapControl.container.style.cursor = _scriptLocation + "../images/cur_PointQuery.cur";
        } else {
            mapControl.workLayer.style.cursor = "url(images/cur_PointQuery.cur),auto";
        };
        this.mapControl.ClearHighlight();
        actionStarted = true;
        this.coordscount = num;
        i = 0;
        str = "";
    }

    this.OnClick = function(e) {
        if (actionStarted) {
            if (i == 0) {
                Coords[i] = e.mapCoord;
                MapControl1.CustomLayer.InsertMark("BusQueryMapCoordMark" + i, e.mapCoord.x, e.mapCoord.y, 10, 10, "<img id='BusQueryMapCoordMark"
                        + i + "' src='images/hotball.gif' />")
                var textStart = document.getElementById("startStop");
                if (!textStart) { return; }
                textStart.value = Coords[i].x + "," + Coords[i].y;
            } else if (i == this.coordscount - 1) {
                Coords[i] = e.mapCoord;
                MapControl1.CustomLayer.InsertMark("BusQueryMapCoordMark" + i, e.mapCoord.x, e.mapCoord.y, 10, 10, "<img id='BusQueryMapCoordMark"
                        + i + "' src='images/hotball.gif' />")
                var textEnd = document.getElementById("endStop");
                if (!textEnd) { return; }
                textEnd.value = Coords[i].x + "," + Coords[i].y;
            } else {
                return;
            }
            i++;
        }
    };

    //重新SetAction时执行Destroy销毁上一个Action
    this.Destroy = function() {
        this.coordscount = null;
        var actionStarted = false;
        var Coords = null;
        var i = null;
    }

    this.GetJSON = function() {
        return _ActionToJSON(this.type, []);
    }
};

function DrawPolygon() {
    if (!drawPolygonAction) {
        drawPolygonAction = new DrawPolygonAction();
    }
    MapControl1.SetAction(drawPolygonAction);
}

function DrawLine() {
    if (!drawLineAction) {
        drawLineAction = new DrawLineAction();
    }
    MapControl1.SetAction(drawLineAction);
}

function DrawPoint() {
    if (!drawPointAction) {
        drawPointAction = new DrawPointAction();
    }
    MapControl1.SetAction(drawPointAction);
}

//绘制多边形
function DrawPolygonAction() {
    this.type = "DrawPolygonAction";
    var actionStarted = false;
    var keyPoints = new Array();
    var xs = new Array();
    var ys = new Array();
    var _self = this;
    var firstMapCoord = null;
    var id = 0;
    this.Init = function(mapControl) {
        this.mapControl = mapControl;
        if (_ygPos.browser == "ie") {
            mapControl.container.style.cursor = _scriptLocation + "../images/cur_PointQuery.cur";
        } else {
            mapControl.workLayer.style.cursor = "url(images/cur_PointQuery.cur),auto";
        };
    };
    this.Destroy = function() { this.mapControl.CustomLayer.RemovePolygon("DrawPolygon"); this.mapControl = null; };

    this.OnClick = function(e) {
        if (!actionStarted) {
            firstMapCoord = e.mapCoord;
            xs.push(e.mapCoord.x); ys.push(e.mapCoord.y);

        } else {
            xs.pop(); ys.pop();
            xs.push(e.mapCoord.x); ys.push(e.mapCoord.y);
        }
        actionStarted = true;
        keyPoints.push(e.mapCoord);
        xs.push(firstMapCoord.x); ys.push(firstMapCoord.y);
    };
    this.OnDblClick = function(e) {
        keyPoints.push(e.mapCoord);
        keyPoints.push(firstMapCoord);
        xs.pop(); ys.pop();
        xs.push(e.mapCoord.x); ys.push(e.mapCoord.y);
        xs.push(firstMapCoord.x); ys.push(firstMapCoord.y);

        while (this.mapControl.CustomLayer.GetGeometry("customPolygon" + id)) {
            id++;
        }
        var geo = new SuperMap.IS.Geometry();
        geo.feature = SuperMap.IS.FeatureType.polygon;
        geo.parts = new Array();
        geo.parts.push(keyPoints.length);
        geo.points = new Array();
        for (var i = 0; i < keyPoints.length; i++) {
            geo.points.push(keyPoints[i]);
        }
        this.mapControl.CustomLayer.RemovePolygon("DrawPolygon");

        SetDefaultStyle();
        MapControl1.CustomLayer.AddGeometry("customPolygon" + id, geo, defaultStyle, null, null, null, OnGeometryMouseOver, OnGeometryMouseOut);
        MapControl1.CustomLayer.UpdateGeometries();
        MapControl1.CustomLayer.SetGeometryTolerance(10);
        while (keyPoints.length > 0) {
            keyPoints.pop();
            xs.pop(); ys.pop();
        }
        firstMapCoord = null;
        actionStarted = false;

        //geoObject包括id,title,description,geo(geometry),style属性
        var geoObject = new Object();
        geoObject.id = "customPolygon" + id;
        geoObject.title = resource_noNamePolygon;
        geoObject.description = "";
        geoObject.geo = geo;
        geoObject.style = defaultStyle;
        geometryObjects.push(geoObject);
        ShowInputInfoDiv("customPolygon" + id, e, geoObject.title, geoObject.description);
    }

    this.OnMouseMove = function(e) {
        if (!actionStarted) { return false; }
        keyPoints.pop();
        xs.pop(); ys.pop();
        keyPoints.push(e.mapCoord);
        xs.push(e.mapCoord.x); ys.push(e.mapCoord.y);
        MapControl1.CustomLayer.InsertPolygon("DrawPolygon", xs, ys, 1, "red", "white", 1, 1);
        e.cancelTriggerGeometryEvent = true;
    };
    this.OnMouseDown = function(e) { };
    this.OnMouseUp = function(e) { };
    this.OnContextMenu = function(e) { };
    this.GetJSON = function() {
        return _ActionToJSON(this.type, []);
    }
};

//绘制线
function DrawLineAction() {
    this.type = "DrawLineAction";
    var actionStarted = false;
    var keyPoints = new Array();
    var xs = new Array();
    var ys = new Array();
    var _self = this;
    var id = 0;
    this.Init = function(mapControl) {
        this.mapControl = mapControl;
        if (_ygPos.browser == "ie") {
            mapControl.container.style.cursor = _scriptLocation + "../images/cur_PointQuery.cur";
        } else {
            mapControl.workLayer.style.cursor = "url(images/cur_PointQuery.cur),auto";
        };
    };
    this.Destroy = function() { this.mapControl.CustomLayer.RemoveLine("DrawLine"); this.mapControl = null; };

    this.OnClick = function(e) {
        if (!actionStarted) {
            keyPoints.push(e.mapCoord);
            xs.push(e.mapCoord.x);
            ys.push(e.mapCoord.y);
        }
        actionStarted = true;
        keyPoints.push(e.mapCoord);
        xs.push(e.mapCoord.x);
        ys.push(e.mapCoord.y);
    };

    this.OnDblClick = function(e) {
        keyPoints.push(e.mapCoord);
        xs.pop(); ys.pop();
        xs.push(e.mapCoord.x); ys.push(e.mapCoord.y);
        while (this.mapControl.CustomLayer.GetGeometry("customLine" + id)) {
            id++;
        }
        var geo = new SuperMap.IS.Geometry();
        geo.feature = SuperMap.IS.FeatureType.line;
        geo.parts = new Array();
        geo.parts.push(keyPoints.length);
        geo.points = new Array();
        for (var i = 0; i < keyPoints.length; i++) {
            geo.points.push(keyPoints[i]);
        }
        this.mapControl.CustomLayer.RemoveLine("DrawLine");

        SetDefaultStyle();
        MapControl1.CustomLayer.AddGeometry("customLine" + id, geo, defaultStyle, null, null, null, OnGeometryMouseOver, OnGeometryMouseOut);
        MapControl1.CustomLayer.UpdateGeometries();
        MapControl1.CustomLayer.SetGeometryTolerance(10);
        while (keyPoints.length > 0) {
            keyPoints.pop();
            xs.pop(); ys.pop();
        }
        actionStarted = false;

        var geoObject = new Object();
        geoObject.id = "customLine" + id;
        geoObject.title = resource_noNameLine;
        geoObject.description = "";
        geoObject.geo = geo;
        geoObject.style = defaultStyle;
        geometryObjects.push(geoObject);
        ShowInputInfoDiv("customLine" + id, e, geoObject.title, geoObject.description);
    }

    this.OnMouseMove = function(e) {
        if (!actionStarted) { return false; }
        keyPoints.pop();
        xs.pop(); ys.pop();
        keyPoints.push(e.mapCoord);
        xs.push(e.mapCoord.x); ys.push(e.mapCoord.y);
        MapControl1.CustomLayer.InsertLine("DrawLine", xs, ys, 1, "red", 1, 1);
        e.cancelTriggerGeometryEvent = true;
    };
    this.OnMouseDown = function(e) { };
    this.OnMouseUp = function(e) { };
    this.OnContextMenu = function(e) { };
    this.GetJSON = function() {
        return _ActionToJSON(this.type, []);
    }
};

//绘制点
function DrawPointAction() {
    this.type = "DrawPointAction";
    var actionStarted = false;
    var _self = this;
    var id = 0;
    this.Init = function(mapControl) {
        this.mapControl = mapControl;
        if (_ygPos.browser == "ie") {
            mapControl.container.style.cursor = _scriptLocation + "../images/cur_PointQuery.cur";
        } else {
            mapControl.workLayer.style.cursor = "url(images/cur_PointQuery.cur),auto";
        };
    };
    this.Destroy = function() { this.mapControl.CustomLayer.RemoveMark("DrawMark"); this.mapControl = null; };

    this.OnClick = function(e) {
        while (this.mapControl.CustomLayer.GetGeometry("customPoint" + id)) {
            id++;
        }
        var geo = new SuperMap.IS.Geometry();
        geo.feature = SuperMap.IS.FeatureType.point;
        geo.parts = new Array();
        geo.parts.push(1);
        geo.points = new Array();
        geo.points.push(e.mapCoord);

        SetDefaultStyle();
        MapControl1.CustomLayer.AddGeometry("customPoint" + id, geo, defaultStyle, null, null, null, OnGeometryMouseOver, OnGeometryMouseOut);
        MapControl1.CustomLayer.UpdateGeometries();
        MapControl1.CustomLayer.SetGeometryTolerance(10);

        var geoObject = new Object();
        geoObject.id = "customPoint" + id;
        geoObject.title = resource_noNamePoint;
        geoObject.description = "";
        geoObject.geo = geo;
        geoObject.style = defaultStyle;
        geometryObjects.push(geoObject);
        ShowInputInfoDiv("customPoint" + id, e, geoObject.title, geoObject.description);
    }

    this.OnDblClick = function() { };
    this.OnMouseMove = function(e) { };
    this.OnMouseDown = function(e) { };
    this.OnMouseUp = function(e) { };
    this.OnContextMenu = function(e) { };
    this.GetJSON = function() {
        return _ActionToJSON(this.type, []);
    }
};

//删除当前Geometry
function RemoveGeometry(geometryId) {
    MapControl1.CustomLayer.RemoveGeometry(geometryId);
    MapControl1.CustomLayer.UpdateGeometries();
    HideInputInfoDiv();
    HideDiv();
}

//保存Geometry的信息
function SaveGeometryObject(geometryId) {
    var object = null;
    for (var i = 0; i < geometryObjects.length; i++) {
        if (geometryId == geometryObjects[i].id) {
            object = geometryObjects[i];
            break;
        }
    }
    if (object == null) {
        object = geometryObjects[geometryObjects.length - 1];
        object.id = geometryId;
    }
    object.title = document.getElementById("title").value;
    object.description = document.getElementById("description").value;
    HideInputInfoDiv();
}

function OnGeometryMouseOver(e, userContext) {
    if (e.ids != null) {
        for (var i = 0; i < e.ids.length; i++) {
            for (var j = 0; j < geometryObjects.length; j++) {
                if (geometryObjects[j].id == e.ids) {
                    MapControl1.container.style.cursor = "pointer";
                    AddDiv(geometryObjects[j].id, geometryObjects[j].title, geometryObjects[j].description, e);
                    break;
                }
            }
        }
    }
}

function OnGeometryMouseOut(e, userContext) {
    if (e.ids != null) {
        MapControl1.container.style.cursor = "default";
    }
}

//显示输入信息层
function ShowInputInfoDiv(geometryId, e, title, description) {
    HideInputInfoDiv();
    var _title = "";
    var _description = "";
    var div = document.getElementById("show_inputdiv");
    if (!div) {
        div = document.createElement("div");
        div.id = "show_inputdiv";
        div.style.borderRight = "gray 2px solid";
        div.style.borderTop = "gray 2px solid";
        div.style.borderLeft = "gray 2px solid";
        div.style.borderBottom = "gray 2px solid";
        div.style.visibility = "visible";
        div.style.position = "absolute";
        div.style.zIndex = 2000;
        MapControl1.container.parentNode.appendChild(div);
    } else {
        div.style.display = "block";
    }
    if (title != null) {
        _title = title;
    }
    if (description != null) {
        _description = description;
    }
    var html = "<table style='background-color:White;'><tr><td id='inputinfodivtitle' style='width: 180px;height:15px;background-color: lightcyan;' onmousedown='dragContainer=document.getElementById(\"show_inputdiv\");OnMouseDown(event);' onmousemove='OnMouseMove(event);' onmouseup='OnMouseUp(event);' OnMouseOut='OnMouseOut(event);'><span style='font-size: 8pt; '>" + resource_inputInfo + "</span></td>";
    html += "<td style='background-color: lightcyan;'><img id='closeandsavegeometryobject' src='images/expandCollapse.gif' onclick='SaveGeometryObject(\"" + geometryId + "\");'/ ></td></tr>";
    html += "<tr><td style='width: 180px;height:30px;'><span style='font-size: 8pt; '>" + resource_title + " :</span><input id='title' type='text' value='" + _title + "' /></td></tr>";
    html += "<tr><td style='width: 180px;height:30px;'><span style='font-size: 8pt; '>" + resource_description + " :</span><textarea id='description' cols='22' rows='5' >" + _description + "</textarea></td></tr>";
    html += "<tr><td style='width: 180px;height:30px;'><input id='savegeometryobject' type='button' value='" + resource_btnOk + "' onclick='SaveGeometryObject(\"" + geometryId + "\");'/>";
    html += "<input id='removegeometry' type='button' value='" + resource_removeGeometry + "' onclick='RemoveGeometry(\"" + geometryId + "\");'/>";
    html += "<input id='showstylediv' type='button' value='" + resource_styleSetting + "' onclick='ShowStyleDiv(\"" + geometryId + "\");'/></td></tr></table>";
    div.innerHTML = html;
    e = _GetEvent(e);
    var left = e.x;
    var top = e.y;
    if (left + div.offsetWidth > MapControl1.container.clientWidth) {
        left = MapControl1.container.clientWidth - div.offsetWidth;
    }
    if (top + div.offsetHeight > MapControl1.container.clientHeight) {
        top = MapControl1.container.clientHeight - div.offsetHeight;
    }
    div.style.left = left + 5 + "px";
    div.style.top = top + 5 + "px";
}

//隐藏填写信息层
function HideInputInfoDiv() {
    var browser = _GetBrowser();
    var div = document.getElementById("show_inputdiv");
    if (div) {
        div.style.display = "none";
    }
    HideStyleDiv();
}

// 隐藏标签层
function HideDiv() {
    var browser = _GetBrowser();
    var div = document.getElementById("show_div");
    if (div) {
        div.style.display = "none";
    }
}


// 在一个层上显示标记信息
function AddDiv(geoId, title, description, e) {
    HideDiv();
    var showdiv = document.getElementById("show_inputdiv");
    if (showdiv.style.display != "none") { return; }
    var div = document.getElementById("show_div");
    if (!div) {
        div = document.createElement("div");
        div.id = "show_div";
        div.style.borderRight = "gray 2px solid";
        div.style.borderTop = "gray 2px solid";
        div.style.borderLeft = "gray 2px solid";
        div.style.borderBottom = "gray 2px solid";
        div.style.visibility = "visible";
        div.style.position = "absolute";
        div.style.zIndex = 1000;
        MapControl1.container.parentNode.appendChild(div);
    } else {
        div.style.display = "block";
    }
    var t = Encoder(title);
    var d = Encoder(description);
    var html = "<table style='background-color:White;'><tr><td style='width: 150px;height:15px;background-color: lightcyan;'><span style='font-size: 10pt;'>" + title.slice(0, 40) + "</span></td>";
    html += "<td style='background-color: lightcyan;'><img id='showinputinfodiv' src='images/link.gif' onclick='HideDiv();ShowInputInfoDiv(\"" + geoId + "\",null,\"" + t + "\",\"" + d + "\");' title=\"" + resource_modify + "\" /></td>";
    html += "<td style='background-color: lightcyan;'><img id='hidediv' src='images/expandCollapse.gif' onclick='HideDiv();' /></td></tr>";
    html += "<tr><td style='width: 150px;height:15px;'><textarea id='readonlydescription' cols='20' rows='5' readonly='true' >" + description + "</textarea></td></tr></table>";
    div.innerHTML = html;
    e = _GetEvent(e);
    var left = e.x;
    var top = e.y;
    if (left + div.offsetWidth > MapControl1.container.clientWidth) {
        left = MapControl1.container.clientWidth - div.offsetWidth;
    }
    if (top + div.offsetHeight > MapControl1.container.clientHeight) {
        top = MapControl1.container.clientHeight - div.offsetHeight;
    }
    div.style.left = left + 10 + "px";
    div.style.top = top + 10 + "px";
}

//字符串替换
function Encoder(str) {
    var html = str.replace(/\"/g, "&#92;&#34;");
    html = html.replace(/\'/g, "&#92;&#39;");
    html = html.replace(/\r/g, "&#92;r");
    html = html.replace(/\n/g, "&#92;n");
    html = html.replace(/\\/g, "&#92;&#92;");
    return html;
}

//显示样式设置DIV
function ShowStyleDiv(geometryid) {
    var count = 0;
    HideStyleDiv();
    var div = document.getElementById("show_stylediv");
    if (!div) {
        div = document.createElement("div");
        div.id = "show_stylediv";
        div.style.left = "300px";
        div.style.top = "200px";
        div.style.borderRight = "gray 2px solid";
        div.style.borderTop = "gray 2px solid";
        div.style.borderLeft = "gray 2px solid";
        div.style.borderBottom = "gray 2px solid";
        div.style.visibility = "visible";
        div.style.position = "absolute";
        div.style.zIndex = 2000;
        document.forms[0].appendChild(div);
    } else {
        div.style.display = "block";
    }
    var geo = new SuperMap.IS.Geometry();
    for (var i = 0; i < geometryObjects.length; i++) {
        if (geometryObjects[i].id == geometryid) {
            geo = geometryObjects[i].geo;
            break;
        }
    }
    if (geo.style) {
        var html = "<table style='background-color:White;'><tr><td colspan='2' id='styledivtitle' style='width: 120px;height:15px;background-color: lightcyan;' onmousedown='dragContainer=document.getElementById(\"show_stylediv\");OnMouseDown(event);' onmousemove='OnMouseMove(event);' onmouseup='OnMouseUp(event);' OnMouseOut='OnMouseOut(event);' ><span style='font-size: 8pt; '>" + resource_styleSetting + "</span></td>";
        html += "<td style='background-color: lightcyan;'><img id='hidestylediv' src='images/expandCollapse.gif' onclick='HideStyleDiv();'/ ></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_brushStyle + "</span>   </td><td><img id='brushstyle' value='" + geo.style.brushStyle + "' style='width:46px;height: 20px; border: 1px solid black;' onclick='GetResource(0,\"brush\");' src='" + GetResourceImage(brushResource, geo.style.brushStyle, 'brush') + "'/></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_brushColor + "</span>   </td><td><input id='brushcolor' style='background-color: " + ConvertIntegerColorToHexColor(geo.style.brushColor) + "; height: 20px; width: 50px' type='button' onclick='ShowColorPanel(\"brushcolor\");' /></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_brushBackColor + "</span>    </td><td><input id='brushbackcolor' style='background-color: " + ConvertIntegerColorToHexColor(geo.style.brushBackColor) + "; height: 20px; width: 50px' type='button' onclick='ShowColorPanel(\"brushbackcolor\");' /></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_penStyle + "</span>    </td><td><img id='penstyle' value='" + geo.style.penStyle + "' style='width:46px;height: 20px; border: 1px solid black;' onclick='GetResource(0,\"pen\");' src='" + GetResourceImage(penResource, geo.style.penStyle, 'pen') + "'/></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_penColor + "</span>    </td><td><input id='pencolor' style='background-color: " + ConvertIntegerColorToHexColor(geo.style.penColor) + "; height: 20px; width: 50px' type='button' onclick='ShowColorPanel(\"pencolor\");' /></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_penWidth + "</span>   </td><td><input id='penwidth' style='height: 15px; width: 50px' type='text' value='" + geo.style.penWidth + "'/></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_symbolStyle + "</span>   </td><td><img id='symbolstyle' value='" + (geo.style.symbolStyle - 3) + "' style='height: 20px; border: 1px solid black;' onclick='GetResource(3,\"symbol\");' src='" + GetResourceImage(symbolResource, geo.style.symbolStyle - 3, 'symbol') + "'/></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_symbolSize + "</span>    </td><td><input id='symbolsize' style='height: 15px; width: 50px' type='text' value='" + geo.style.symbolSize + "'/></td></tr>";
        html += "<tr><td style='height:30px;'><input id='styleconfirm' type='button' value='" + resource_btnOk + "' onclick='SetGeometryStyle(\"" + geometryid + "\");'/></td></tr></table>";
        div.innerHTML = html;
    } else {
        var html = "<table style='background-color:White;'><tr><td colspan='2' id='styledivtitle' style='width: 60px;height:15px;background-color: lightcyan;' onmousedown='dragContainer=document.getElementById(\"show_stylediv\");OnMouseDown(event);' onmousemove='OnMouseMove(event);' onmouseup='OnMouseUp(event);' OnMouseOut='OnMouseOut(event);' ><span style='font-size: 8pt; '>" + resource_styleSetting + "</span></td>";
        html += "<td style='background-color: lightcyan;'><img id='hidestylediv' src='images/expandCollapse.gif' onclick='HideStyleDiv();'/ ></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_brushStyle + "</span></td><td><img id='brushstyle' value=0 style='width:46px; height: 20px; border: 1px solid black;' onclick='GetResource(0,\"brush\");' src='images/DefaultFillStyle.png'/></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_brushColor + "</span></td><td><input id='brushcolor' style='background-color: #ffffff; height: 20px; width: 50px' type='button' onclick='ShowColorPanel(\"brushcolor\");' /></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_brushBackColor + "</span></td><td><input id='brushbackcolor' style='background-color: #ffffff; height: 20px; width: 50px' type='button' onclick='ShowColorPanel(\"brushbackcolor\");' /></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_penStyle + "</span></td><td><img id='penstyle' value=0 style='width:46px;height: 20px; border: 1px solid black;' onclick='GetResource(0,\"pen\");' src='images/DefaultLineStyle.png'/></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_penColor + "</span></td><td><input id='pencolor' style='background-color: #ff0000; height: 20px; width: 50px' type='button' onclick='ShowColorPanel(\"pencolor\");' /></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_penWidth + "</span></td><td><input id='penwidth' style='height: 15px; width: 50px' type='text' value='" + defaultStyle.penWidth + "'/></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_symbolStyle + "</span></td><td><img id='symbolstyle' value=0 style='height: 20px; border: 1px solid black;' onclick='GetResource(3,\"symbol\");' src='images/DefaultSymbol.png'/></td></tr>";
        html += "<tr><td style='height:30px;'><span style='font-size: 8pt; '>" + resource_symbolSize + "</span></td><td><input id='symbolsize' style='height: 15px; width: 50px' type='text' value='" + defaultStyle.symbolSize + "'/></td></tr>";
        html += "<tr><td style='height:30px;'><input id='styleconfirm' type='button' value='" + resource_btnOk + "' onclick='SetGeometryStyle(\"" + geometryid + "\");'/></td></tr></table>";
        div.innerHTML = html;
    }
}

function GetResourceImage(resources, resourceId, resourceType) {
    if (resources[resourceId]) {
        return resources[resourceId];
    } else {
        switch (resourceType) {
            case "brush":
                return "images/DefaultFillStyle.png";
                break;
            case "pen":
                return "images/DefaultLineStyle.png";
                break;
            case "symbol":
                return "images/DefaultSymbol.png";
                break;
        }
    }
}

//获取资源图片
function GetResource(styleId, type) {
    var rp = new SuperMap.IS.ResourceParam();
    rp.imageFormat = 0;
    rp.style = new SuperMap.IS.Style();
    switch (type) {
        case "brush":
            rp.height = 20;
            rp.width = 50;
            rp.resourceType = 2;
            rp.style.brushStyle = styleId;
            break;
        case "pen":
            rp.height = 20;
            rp.width = 50;
            rp.resourceType = 1;
            rp.style.penStyle = styleId;
            break;
        case "symbol":
            rp.height = 20;
            rp.width = 50;
            rp.resourceType = 0;
            rp.style.symbolStyle = styleId;
            break;
    }

    var mapName = MapControl1.GetMapParam().mapName;
    MapControl1.GetResource(mapName, rp, OnGetResourceComplete);
}

function OnGetResourceComplete(e) {
    if (e.toString().indexOf("Fill") != -1) {
        if (brushResource.length < 10) {
            brushResource.push(e);
            GetResource(brushResource.length, "brush");
        }
        else {
            ShowStylePanel("brushstyle")
        }
    }
    else if (e.toString().indexOf("Line") != -1) {
        if (penResource.length < 10) {
            penResource.push(e);
            GetResource(penResource.length, "pen");
        }
        else {
            ShowStylePanel("penstyle")
        }
    }
    else if (e.toString().indexOf("Symbol") != -1) {
        if (symbolResource.length < 10) {
            symbolResource.push(e);
            //由于符号库中没有编号为3的符号风格，所以从编号为3的风格开始取
            GetResource(symbolResource.length + 3, "symbol");
        }
        else {
            ShowStylePanel("symbolstyle")
        }
    }
};

//显示样式面板
function ShowStylePanel(objId) {
    var brushpanel = document.getElementById("show_panelbrushstyle");
    var penpanel = document.getElementById("show_panelpenstyle");
    var symbolpanel = document.getElementById("show_panelsymbolstyle");
    if (brushpanel && objId != "brushstyle") { brushpanel.style.display = "none"; }
    if (penpanel && objId != "penstyle") { penpanel.style.display = "none"; }
    if (symbolpanel && objId != "symbolstyle") { symbolpanel.style.display = "none"; }
    var obj = document.getElementById(objId);
    var panel = document.getElementById("show_panel" + objId);
    if (!panel) {
        panel = document.createElement("div");
        panel.id = "show_panel" + objId;
        panel.style.visibility = "visible";
        panel.style.position = "absolute";
        panel.style.zIndex = 3000;
        obj.parentNode.appendChild(panel);
    } else {
        panel.style.display = panel.style.display == "none" ? "block" : "none";
    }
    var Resource = new Array();
    if (objId.toString().indexOf("brush") != -1) {
        Resource = brushResource;
    }
    if (objId.toString().indexOf("pen") != -1) {
        Resource = penResource;
    }
    if (objId.toString().indexOf("symbol") != -1) {
        Resource = symbolResource;
    }
    var styleTable = '';
    for (i = 0; i < 9; i++) {
        if (i % 3 == 0) {
            styleTable += '<tr height=16>';
            styleTable += '<td id="' + objId + i + '" width=46 style= "backgroundPosition:\'center center\'; background-image:url(' + Resource[i] + ');" onclick="DoStyleClick(\'' + objId + '\',' + i + ');"></td>';
        }
        if (i % 3 == 1) {
            styleTable += '<td id="' + objId + i + '" width=46 style= "backgroundPosition:\'center center\'; background-image:url(' + Resource[i] + ');" onclick="DoStyleClick(\'' + objId + '\',' + i + ');"></td>';
        }
        if (i % 3 == 2) {
            styleTable += '<td id="' + objId + i + '" width=46 style= "backgroundPosition:\'center center\'; background-image:url(' + Resource[i] + ');" onclick="DoStyleClick(\'' + objId + '\',' + i + ');"></td>';
            styleTable += "</tr>";
        }
    }
    styleTable = '<table border="1" cellspacing="0" cellpadding="0" style="border-collapse: collapse;width:120px; " bordercolor="000000" style="cursor:pointer;" DoStyleClick(\'' + objId + '\',' + i + ');>' + styleTable + '</table>';
    panel.innerHTML = styleTable;
}

function DoStyleClick(objId, resourceId) {
    var obj = document.getElementById(objId);
    obj.value = resourceId;
    var td = document.getElementById(objId.toString() + resourceId.toString());
    var temp = td.style.backgroundImage.toString().split("(");
    var url = temp[1].split(")");
    //replace双引号来兼容opera
    obj.src = url[0].replace(/\"/g, "");
    obj.style.backgroundPosition = "center center";
    var div = document.getElementById("show_panel" + objId);
    if (div) {
        div.style.display = "none";
    }
}

//生成颜色面板
function ShowColorPanel(objId) {
    var obj = document.getElementById(objId);
    var colorpanel = document.getElementById("show_colorpanel");
    if (colorpanel != null) {
        if (colorpanel.parentNode == obj.parentNode) {
            colorpanel.style.display = colorpanel.style.display == "none" ? "block" : "none";
            return;
        }
        colorpanel.style.display = "block";
        colorpanel.parentNode.removeChild(colorpanel);
        obj.parentNode.appendChild(colorpanel);
        return;
    }
    colorpanel = document.createElement("div");
    colorpanel.id = "show_colorpanel";
    colorpanel.style.visibility = "visible";
    colorpanel.style.position = "absolute";
    colorpanel.style.zIndex = 3000;
    var colorTable = '';
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 6; j++) {
            colorTable = colorTable + '<tr height=12>';
            colorTable = colorTable + '<td id="' + objId + i + j + '1" width=11 style="background-color:#000000" onmouseover="DoColorOver(this)" OnMouseOut="DoColorOut()" onclick="DoColorClick(this,\'' + objId + '\')" />';

            if (i == 0) {
                colorTable = colorTable + '<td id="' + objId + i + j + '2" width=11 style="background-color:#' + colorHex[j] + colorHex[j] + colorHex[j] + '" onmouseover="DoColorOver(this)" OnMouseOut="DoColorOut()" onclick="DoColorClick(this,\'' + objId + '\')" />';
            }
            else {
                colorTable = colorTable + '<td id="' + objId + i + j + '2" width=11 style="background-color:#' + spColorHex[j] + '" onmouseover="DoColorOver(this)" OnMouseOut="DoColorOut()" onclick="DoColorClick(this,\'' + objId + '\')" />';
            }

            colorTable = colorTable + '<td id="' + objId + i + j + '3" width=11 style="background-color:#000000" onmouseover="DoColorOver(this)" OnMouseOut="DoColorOut()" onclick="DoColorClick(this,\'' + objId + '\')" />';
            for (k = 0; k < 3; k++) {
                for (l = 0; l < 6; l++) {
                    colorTable = colorTable + '<td id="' + objId + i + j + k + l + '" width=11 style="background-color:#' + colorHex[k + i * 3] + colorHex[l] + colorHex[j] + '" onmouseover="DoColorOver(this)" OnMouseOut="DoColorOut()" onclick="DoColorClick(this,\'' + objId + '\')" />';
                }
            }
            colorTable = colorTable + '</tr>';
        }
    }
    colorTable = '<table width=253 border="0" cellspacing="0" cellpadding="0" style="border:1px #000000 solid;border-bottom:none;border-collapse: collapse" bordercolor="000000">'
           + '<tr height=30><td colspan=21 bgcolor=#cccccc>'
           + '<table cellpadding="0" cellspacing="1" border="0" style="border-collapse: collapse">'
           + '<tr><td width="3"><input type="text" id="DisColor" size="6" disabled style="border:solid 1px #000000;background-color:#ffff00"></td>'
           + '<td width="3"><input type="text" id="HexColor" size="9" style="border:inset 1px;font-family:Arial;" value="#000000"></td></tr></table></td></tr></table>'
           + '<table width=253 id="myTable" border="1" cellspacing="0" cellpadding="0" style="border-collapse: collapse" bordercolor="000000" style="cursor:pointer;">'
           + colorTable + '</table>';
    colorpanel.innerHTML = colorTable;
    obj.parentNode.appendChild(colorpanel);
}

function DoColorOver(obj) {
    if ((obj.tagName == "TD") && (currentElement != obj)) {
        if (currentElement != null) { currentElement.style.backgroundColor = currentElement._background }
        obj._background = obj.style.backgroundColor
        var DisColor = document.getElementById("DisColor");
        DisColor.style.backgroundColor = obj.style.backgroundColor;
        var HexColor = document.getElementById("HexColor");
        HexColor.value = obj.style.backgroundColor;
        obj.style.backgroundColor = "white";
        currentElement = obj;
    }
}

function DoColorOut(e) {
    if (currentElement != null) currentElement.style.backgroundColor = currentElement._background;
}

function DoColorClick(td, objId) {
    if (td.tagName == "TD") {
        var obj = document.getElementById(objId);
        obj.style.backgroundColor = td._background;
        var div = document.getElementById("show_colorpanel");
        if (div) {
            obj.parentNode.removeChild(div);
        }
    }
}

//将rgb(R,G,B)转换为包含了颜色RGB分量信息的整数
function ConvertRGBColor(rgbColor) {
    var temp = rgbColor.toString().split("(");
    var colorString = temp[1].split(")");
    var colorChar = colorString[0].split(",");
    var red = parseInt(colorChar[0]);
    var green = parseInt(colorChar[1]);
    var blue = parseInt(colorChar[2]);
    return (red + green * 256 + blue * 256 * 256);
}

//将HexColor转换为包含了颜色RGB分量信息的整数
function ConvertHexColor(hexColor) {
    var colorString = hexColor.toString().split("#");
    if (colorString.length < 2) {
        return;
    }
    var colorChar = colorString[1].split("");
    var red = Convertor(colorChar[0]) * 16 + Convertor(colorChar[1]);
    var green = Convertor(colorChar[2]) * 16 + Convertor(colorChar[3]);
    var blue = Convertor(colorChar[4]) * 16 + Convertor(colorChar[5]);
    return (red + green * 256 + blue * 256 * 256);
}

//将包含了颜色RGB分量信息的整数转换为HexColor
function ConvertIntegerColorToHexColor(integerColor) {
    var blue = parseInt(integerColor / (256 * 256));
    var green = parseInt((integerColor - blue * 256 * 256) / 256);
    var red = parseInt(integerColor - blue * 256 * 256 - green * 256);
    var hexRed = red.toString(16);
    if (hexRed.length < 2) { hexRed = "0" + hexRed; }
    var hexGreen = green.toString(16);
    if (hexGreen.length < 2) { hexGreen = "0" + hexGreen; }
    var hexBlue = blue.toString(16);
    if (hexBlue.length < 2) { hexBlue = "0" + hexBlue; }
    return "#" + hexRed + hexGreen + hexBlue;
}

//十六进制数字转换为十进制数字
function Convertor(num) {
    var result = 0;
    switch (num.toLowerCase()) {
        case "f":
            result = 15;
            break;
        case "e":
            result = 14;
            break;
        case "d":
            result = 13;
            break;
        case "c":
            result = 12;
            break;
        case "b":
            result = 11;
            break;
        case "a":
            result = 10;
            break;
        default:
            result = parseInt(num);
            break;
    }
    return result;
}

//隐藏样式设置层
function HideStyleDiv() {
    var browser = _GetBrowser();
    var div = document.getElementById("show_stylediv");
    if (div) {
        div.style.display = "none";
    }
}

//保存样式设置
function SetGeometryStyle(geometryid) {
    var style = new SuperMap.IS.Style();
    style.brushStyle = parseInt(document.getElementById("brushstyle").value);
    if (document.getElementById("brushcolor").style.backgroundColor.toString().indexOf("rgb") != -1) {
        style.brushColor = ConvertRGBColor(document.getElementById("brushcolor").style.backgroundColor);
    }
    else {
        style.brushColor = ConvertHexColor(document.getElementById("brushcolor").style.backgroundColor);
    }
    if (document.getElementById("brushbackcolor").style.backgroundColor.toString().indexOf("rgb") != -1) {
        style.brushBackColor = ConvertRGBColor(document.getElementById("brushbackcolor").style.backgroundColor);
    }
    else {
        style.brushBackColor = ConvertHexColor(document.getElementById("brushbackcolor").style.backgroundColor);
    }
    style.penStyle = parseInt(document.getElementById("penstyle").value);
    if (document.getElementById("pencolor").style.backgroundColor.toString().indexOf("rgb") != -1) {
        style.penColor = ConvertRGBColor(document.getElementById("pencolor").style.backgroundColor);
    }
    else {
        style.penColor = ConvertHexColor(document.getElementById("pencolor").style.backgroundColor);
    }
    style.penWidth = document.getElementById("penwidth").value;
    style.symbolStyle = parseInt(document.getElementById("symbolstyle").value);
    style.symbolSize = parseInt(document.getElementById("symbolsize").value);
    HideStyleDiv();
    var geo = new SuperMap.IS.Geometry();
    for (var i = 0; i < geometryObjects.length; i++) {
        if (geometryObjects[i].id == geometryid) {
            //geo为点时从符号库编号为4的符号开始取符号风格
            if (geometryObjects[i].geo.feature == SuperMap.IS.FeatureType.point) {
                style.symbolStyle += 3;
            }
            geo = geometryObjects[i].geo;
            break;
        }
    }
    geo.style = style;
    MapControl1.CustomLayer.InsertGeometry(geometryid, geo, style, null, null, null, OnGeometryMouseOver, OnGeometryMouseOut);
    MapControl1.CustomLayer.UpdateGeometries();
}

//设置默认样式
function SetDefaultStyle() {
    if (defaultStyle == null) {
        defaultStyle = new SuperMap.IS.Style();
        defaultStyle.brushStyle = 0;
        defaultStyle.brushColor = 16777215;
        defaultStyle.penColor = 255;
        defaultStyle.penWidth = 2;
        defaultStyle.symbolSize = 50;
    }
}

//拖动DIV
function OnMouseDown(e) {
    oldMousePositionX = e.clientX - dragContainer.offsetLeft;
    oldMousePositionY = e.clientY - dragContainer.offsetTop;
    startMoving = true;
    dragContainer.style.cursor = "move";
    return false;
}

function OnMouseMove(e) {
    if (!startMoving) { return false; }
    var offsetX = e.clientX - oldMousePositionX;
    var offsetY = e.clientY - oldMousePositionY;
    dragContainer.style.left = offsetX + "px";
    dragContainer.style.top = offsetY + "px";
    return false;
}

function OnMouseUp(e) {
    if (dragContainer != null) {
        startMoving = false;
        dragContainer.style.cursor = "default";
        dragContainer = null;
        return false;
    }
}

function OnMouseOut(e) {
    if (dragContainer != null) {
        startMoving = false;
        dragContainer.style.cursor = "default";
        dragContainer = null;
        return false;
    }
}

//清除所有图形
function ClearGeometries() {
    MapControl1.CustomLayer.ClearGeometries();
    MapControl1.CustomLayer.UpdateGeometries();
    while (geometryObjects.length > 0) {
        geometryObjects.pop();
    }
    HideInputInfoDiv();
    HideStyleDiv();
    HideDiv();
}

function FillDynamicMapForm() {
    if (!m_workspace) {
        MapControl1.GetWorkspaceInfo(OnGetWorkspaceInfoComplete, OnActionError, "GetWorkspaceInfo");
        return;
    }
    FillDynamicMapFormInternal();
}

function FillDynamicMapFormInternal() {
    FillDatasourceList();
    FillDatasetList(0);
}

function FillDatasourceList() {
    var datasourceList = document.getElementById("SelectDatasouce");
    while (datasourceList.options.length > 0) {
        datasourceList.options[0] = null;
    }
    if (m_workspace.datasources) {
        for (var i = 0; i < m_workspace.datasources.length; i++) {
            var mnOption = document.createElement("OPTION");
            datasourceList.options.add(mnOption);
            mnOption.innerText = m_workspace.datasources[i].alias;
            mnOption.value = m_workspace.datasources[i].alias;
            if (i == 0) {
                mnOption.selected = true;
            }
            else {
                mnOption.selected = false;
            }
        }
    }
}

function FillDatasetList(datasourceIndex) {
    var doc = document;
    var datasourceList = doc.getElementById("SelectDatasouce");
    var datasourceName = datasourceList.value;
    var datasetList = doc.getElementById("SelectDataset");
    while (datasetList.options.length > 0) {
        datasetList.options[0] = null;
    }
    if (m_workspace.datasources[datasourceIndex]) {
        if (m_workspace.datasources[datasourceIndex].datasets) {
            var datasets = m_workspace.datasources[datasourceIndex].datasets;
            for (var i = 0; i < datasets.length; i++) {
                var mnOption = document.createElement("OPTION");
                datasetList.options.add(mnOption);
                mnOption.innerText = datasets[i].name;
                mnOption.value = datasets[i].name + "@" + datasourceName;
                if (i == 0) {
                    mnOption.selected = true;
                }
                else {
                    mnOption.selected = false;
                }
            }
        }
    }
}

function ReFillDatasetList() {
    var datasourceList = document.getElementById("SelectDatasouce");
    FillDatasetList(datasourceList.selectedIndex);
}

function OnGetWorkspaceInfoComplete(workspace) {
    if (workspace) {
        if (m_workspace != null) {
            m_workspace.Destroy();
            m_workspace = null;
        }
        m_workspace = new SuperMap.IS.Workspace();
        m_workspace.FromJSON(workspace);
        FillDynamicMapFormInternal();
    }
    else {
        alert(resource_getWorkspaceInfoError + "!");
    }
}

function ViewDataset() {
    //先备份地图图层
    if (!m_layers) {
        m_layers = new Array();
        for (var i = 0; i < MapControl1.layers.length; i++) {
            var layer = new SuperMap.IS.Layer();
            layer.FromJSON(MapControl1.layers[i]);
            m_layers.push(layer);
        }
    }
    var datasetList = document.getElementById("SelectDataset");
    while (MapControl1.layers.length > 0) {
        var layer = MapControl1.layers.pop();
        layer.Destroy();
        layer = null;
    }
    var layer = new SuperMap.IS.Layer();
    layer.name = datasetList.value;
    layer.caption = datasetList.value;
    layer.visible = true;
    var layerInfo = layer.name.split("@");
    for (var i = 0; i < m_workspace.datasources.length; i++) {
        if (m_workspace.datasources[i].datasets && m_workspace.datasources[i].alias == layerInfo[1]) {
            var datasets = m_workspace.datasources[i].datasets;
            for (var j = 0; j < datasets.length; j++) {
                if (datasets[j].name == layerInfo[0]) {
                    layer.type = datasets[j].type;
                    layer.style = new SuperMap.IS.Style();
                    //随机风格显示,防止缓存
                    layer.style.brushColor = Math.floor(Math.random() * 16777215);
                    layer.style.penColor = Math.floor(Math.random() * 16777215);
                    break;
                }
            }
            break;
        }
    }
    MapControl1.layers.push(layer);
    MapControl1.Update();
}

function ResetMap() {
    if (m_layers) {
        while (MapControl1.layers.length > 0) {
            var layer = MapControl1.layers.pop();
            layer.Destroy();
            layer = null;
        }
        for (var i = 0; i < m_layers.length; i++) {
            var layer = new SuperMap.IS.Layer();
            layer.FromJSON(m_layers[i]);
            MapControl1.layers.push(layer);
        }
        MapControl1.Update();
    }
}

function RefreshWorkspace() {
    MapControl1.GetWorkspaceInfo(OnGetWorkspaceInfoComplete, OnActionError, "GetWorkspaceInfo");
}

//地图编辑操作中获得改变后的图层
function SwitchLayer() {
    var actionType = MapControl1.GetAction().type;
    var infos = document.getElementById("EditLayers").value.split(',');
    if (actionType == "SuperMap.IS.AddEntityAction"
    || actionType == "SuperMap.IS.DeleteEntityAction"
    || actionType == "SuperMap.IS.MoveEntityAction"
    || actionType == "SuperMap.IS.UpdateEntityAction") {
        MapControl1.GetAction().SetEditLayer(infos[0], eval(infos[1]));
    }
}

function OnActionError(responseText, userContext) {
    switch (userContext) {
        case "SuperMap.IS.MeasureDistanceAction":
            OnActionErrorDo(resource_measureDistanceError, responseText);
            break;
        case "SuperMap.IS.MeasureAreaAction":
            OnActionErrorDo(resource_maesureAraeError, responseText);
            break
        case "SuperMap.IS.FindPathAction":
            OnActionErrorDo(resource_findPathError, responseText);
            break;
        case "SuperMap.IS.PointQueryAction":
        case "SuperMap.IS.LineQueryAction":
        case "SuperMap.IS.CircleQueryAction":
        case "SuperMap.IS.RectQueryAction":
        case "SuperMap.IS.PolygonQueryAction":
            OnActionErrorDo(resource_queryError, responseText);
            break;
        case "GetBusSolutionByPoints":
        case "GetBusSolutionByNames":
        case "GetBusSolutionByIds":
            OnActionErrorDo(resource_busSolutionError, responseText);
            break;
        case "GetBusLinesByStopID":
            OnActionErrorDo(resource_getBusLinesByStopID, responseText);
            break;
        case "GetWorkspaceInfo":
            OnActionErrorDo(resource_getWorkspaceInfoError, responseText);
            break;
        case "ShowBusStop":
            OnActionErrorDo(resource_showBusStopError, responseText);
            break;
        case "ShowBusLine":
            OnActionErrorDo(resource_showBusLineError, responseText);
            break;
        case "ShowRouting":
            OnActionErrorDo(resource_showRoutingError, responseText);
            break;
        case "LockLayer":
            OnActionErrorDo(resource_lockLayerError, responseText);
            break;
        case "UnlockLayer":
            OnActionErrorDo(resource_unlockLayerError, responseText);
            break;
        case "AddEntity":
        case "UpdateEntity":
        case "MoveEntity":
        case "DeleteEntity":
            OnActionErrorDo("", responseText);
            break;
        default:
            break;
    }
}

function OnActionErrorDo(ActionError, responseText) {
    if (responseText) {
        if (ActionError) {
            alert(ActionError + ":" + responseText);
        } else {
            alert(responseText);
        }
    } else {
        alert(ActionError + "!");
    }
}

function OnPageUnload() {
   var infos = "L_TieLu";//document.getElementById("EditLayers").value.split(',');
    if (lockID) {
        MapControl1.GetEditManager().UnlockLayer(MapControl1.mapName, infos[0], lockID);
     
    }
}

function ChangeLockLayerImage(status) {
    var lockLayerBtn = document.getElementById("lockLayer");
    var oldsrc = lockLayerBtn.src;
    if (status == "over") {
        lockLayerBtn.src = oldsrc.replace(".png", "_on.png");
    } else if (status == "out") {
        lockLayerBtn.src = oldsrc.replace("_on.png", ".png");
    }
}

function LockLayer() {
    var infos = document.getElementById("EditLayers").value.split(',');

    function onLockLayerComplete(userID) {
        lockID = userID;
        if (!userID) {
            OnActionError(infos[0], "LockLayer");
            return;
        }
        if (userID) {
            var lockLayerBtn = document.getElementById("lockLayer");
            lockLayerBtn.src = "images/unlockLayer.png";
            lockLayerBtn.onclick = UnlockLayer;
            var editLayers = document.getElementById("EditLayers");
            editLayers.disabled = true;
        }
    }

    function onLockLayerError(responseText) {
        OnActionError(responseText, "LockLayer");
    }

    if (!lockID) {
        lockID = Math.floor(Math.random() * 10000);
    }

    MapControl1.GetEditManager().LockLayer(MapControl1.mapName, infos[0], lockID, onLockLayerComplete, onLockLayerError);
}

function UnlockLayer() {
    var infos = document.getElementById("EditLayers").value.split(',');

    function onUnlockLayerComplete(succeed) {
        if (succeed) {
            lockID = null;
            var lockLayerBtn = document.getElementById("lockLayer");
            lockLayerBtn.src = "images/lockLayer.png";
            lockLayerBtn.onclick = LockLayer;
            var editLayers = document.getElementById("EditLayers");
            editLayers.disabled = false;
        }
        if (lockID && !succeed) {
            OnActionError(infos[0], "UnlockLayer");
        }
    }

    function onUnlockLayerError(responseText) {
        OnActionError(responseText, "UnlockLayer");
    }

    if (lockID) {
        MapControl1.GetEditManager().UnlockLayer(MapControl1.mapName, infos[0], lockID, onUnlockLayerComplete, onUnlockLayerError);
    }
}